# Question
Title: How do I show login form to anonymous user when accessing particular form
I have created an entry form. Only authenticated user can access it. I have created a menu link for it and if any anonymous user clicks on menu link I want to show a login form and after successful login user is redirected to that entry form. I don't want to hide the menu link from anonymous user.(I have about 5 to 6 forms with same condition)

# Answer
```

?php
          global $user;
          //Redirect original Page
          $redirect = 'destination='.drupal_get_path_alias(substr(urldecode(  drupal_get_destination()), 12) );
          if ($user->uid)
          {
                        header('Location:?q=node/nodename');   //If user is logged in. Go to specific destination
          }
         else
          {
          //If user is not logged in. Show him login or register
                       $login_link = l(t('Login'), 'user', array( 'query' => $redirect, 'alias' => TRUE ));
$register_link = l(t('Register'), 'user/register', array( 'query' => $redirect, 'alias' => TRUE ));
$user_utilities = '

' . $login_link . '
' . $register_link;
}
echo "**You are not Registered User. Please Login** ";
return $user_utilities;
?>

```
> 0 votes

# Answer
Logintoboggan will allow you display a login form when a user hits an access denied page:

> Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
> 8 votes

---
Tags: users
---


title: Determine if node is new

text:
# Question
Title: Determine if node is new
I am inserting nodes from an external application into Drupal (7.x). I've taken care of the node\_revision table and other tables needed by Drupal to see the node. However I have pathauto installed and it does not recognize the node as new as per this link. So my question is, how does Drupal/Pathauto determine if a node is new or not?

Obviously I can't use the `$node->is_new` property, cause I am doing the inserts from a Zend application. I just want Pathauto to check the `Automatic alias` checkbox by default.

# Answer
Pathauto reacts on node save, which doesn't happen when you insert directly via SQL. Pass data from your external application to a custom hook\_menu entry, assemble the node from $\_GET-data, and run node\_save($node), instead of inserting it directly.

Second option, if to enable Services, which allows you to pass data in as json, and have the nodes created that way.

I belive both ways will properly trigger Core hooks, so that pathauto will be called.
> 4 votes

# Answer
When a node is created (using the UI or imported), Drupal sets a datestamp in his database. In the `node` table, there is a `created` field. An encoded timestamp is located there.

When you're building a view or some custom code to show the new nodes, Drupal knows which nodes to select because the system simply calculates the difference between today's timestamp and that of the node.
> 0 votes

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


# Question
Title: Adding external databases to settings.php using prefix
As per the comments in settings.php:

```
/*
 * You can also use a reference to a schema/database as a prefix. This maybe
 * useful if your Drupal installation exists in a schema that is not the default
 * or you want to access several databases from the same code base at the same
 * time.
 * Example:
 * @code
 *   'prefix' => array(
 *     'default'   => 'main.',
 *     'users'     => 'shared.',
 *     'sessions'  => 'shared.',
 *     'role'      => 'shared.',
 *     'authmap'   => 'shared.',
 *   );
 * @endcode
 */

```

So if my current simple default looks like:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dev',
      'username' => 'dev',
      'password' => 'dev',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => false,
    ),
  ),
);

```

How would I add two tables (table1 and table2) on another database (dev1) on localhost so that they are available to drupal?

# Answer
If they're on the same mysql host (and you've got the appropriate permissions) you can access the tables by simply prefixing them with the schema name: `otherdatabasename.tablename`. You can even run queries joining across the two databases.

If they're on a different server you'll need to add a separate connection and specify it as part of the query by using the $options\['target'\] setting.
> 3 votes

---
Tags: configuration, database
---


# Question
Title: Use views to produce list of terms with descriptions
I have a Tags taxonomy which includes a couple of terms with *descriptions*.

Tags are rendered in a simple inline list under the content, and this is fine for most of them.

But some terms are acting as flags, e.g. "needs update", "stub". For these, just being listed at the bottom is not enough.

I would like to make a view block that lists **all terms that have descriptions** (and not ones that don't). I plan to then stick this at the top of the Content section and use a contextual filter so that if a page is tagged "needs update" you get a warning at the top of the page explaining what this tag means. Just like wikipedia does for "This page is a *stub* \- it needs more info...".

Problem: views 3 (on Drupal 7) does not appear to be able to add term:description as a filter.

# Answer
A easy workaround could be to attach a regular text-field to the terms, instead of using the hardcoded description.

**Update:** After taking a quick peek in the code, it does look like filtering on descriptions are not supported. This could just be a simple oversight. There's an issue here, which claims this functionality has been added. I can't seem to find it, so I attached a new patch and reopened the issue.

**Update 2:** Dereine has commited my patch to D7. You should now be able to filter on term descriptions with the dev version.
> 4 votes

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


title: Using Newsletter module question

text:
# Question
Title: Using Newsletter module question
I have just installed the Newsletter module, and I am wondering if it is possible to allow users to click on a "subscribe" button, and have them signup for a newsletter, rather than have an administrator manually add subscribers.

# Answer
The newsletter module already has this built in by default.

1. Go into permissions and enable "Subscribe newsletters" to all roles.

2. Then, go to the Blocks UI and enable the "Newsletter: Subscribe" into the region of your choosing.
> 2 votes

---
Tags: 7, emails
---


title: Custom widget making field invisible

text:
# Question
Title: Custom widget making field invisible
I'm trying to create a custom module for Drupal 7 that makes two widgets available for Text fields. The widgets are showing up in the list of available widgets, but when I select one of them as the widget for a Text field, the field isn't visible on the form (although it is still listed in the Manage Fields section and its settings can be changed as normal). Here's my code so far:

```
<?php
/**
 * Implements hook_menu().
 */
function autocomplete_jsb_users_menu() {
    $items['jsbu/speaker/autocomplete'] = array(
        'page callback' => 'jsbu_speaker_autocomplete',
        'access callback' => TRUE,
        'weight' => 1,
    );
    $items['jsbu/venue/autocomplete'] = array(
        'page callback' => 'jsbu_venue_autocomplete',
        'access callback' => TRUE,
        'weight' => 2,
    );
    return $items;
}

/**
 * Implements hook_field_widget_info().
 *
 * Two widgets are provided.
 * - A textfield Speaker name autocomplete widget.
 * - A textfield Venue name autocomplete widget.
 */
function autocomplete_jsb_users_field_widget_info() {
    return array(
        'autocomplete_speaker_name' => array(
            'label' => t('Autocomplete Speaker Name'),
            'field types' => array('text'),
        ),
        'autocomplete_venue_name' => array(
            'label' => t('Autocomplete Venue Name'),
            'field types' => array('text'),
        ),
    );
}

/**
 * Implements hook_field_widget_form().
 */
function autocomplete_jsb_users_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    //load the default text instance
    $element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

    /*if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
        $element['value']['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
    } else if($instance['widget']['type'] == 'autocomplete_venue_name') {
        $element['value']['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }*/
    return $element;
}

/**
 * Implements the autocomplete_jsbu_speaker() callback.
 */
function jsbu_speaker_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_speaker_name', 'sn');

    // Select rows that match the string
    $query
        ->fields('sn', array('field_speaker_name_value'))
        ->orderBy('field_speaker_name_value', 'DESC');

    $result = $query.execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_speaker_name_value] = check_plain($row->field_speaker_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

/**
 * Implements the autocomplete_jsbu_venue() callback.
 */
function jsbu_venue_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_venue_name', 'vn');

    // Select rows that match the string
    $query
        ->fields('vn', array('field_venue_name_value'))
        ->orderBy('field_venue_name_value', 'DESC');

    $result = $query.execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_venue_name_value] = check_plain($row->field_venue_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

```

Any ideas on what I'm doing wrong there/anything else I might need to add? Is the problem that I'm missing a hook?

EDIT: $element just before return:

```
Array (
    [#entity_type] => node
    [#bundle] => event
    [#field_name] => field_event_speaker
    [#language] => und
    [#field_parents] => Array
        (
        )

    [#columns] => Array
        (
            [0] => value
            [1] => format
        )

    [#title] => Speaker
    [#description] =>
    [#required] =>
    [#delta] => 0
    [value] => Array
        (
            [#autocomplete_path] => jsbu/speaker/autocomplete
        )

)

```

# Answer
I think it's because you're missing the type, however, to make things easier and more compatible, why not load the "stock" widget and make modifications?

Try adding this instead of your `$element` declarations:

`$element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);`

That should load the default text form, then you can make modifications. You can take a look at the code it uses directly: see line 502 of text.module.

Your simplified code might look something like this:

```
   //load the default text instance
   $element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

   if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
      $element['value']['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
   else if($instance['widget']['type'] == 'autocomplete_venue_name')
      $element['value']['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }

   return $element;

```
> 2 votes

---
Tags: 7, hooks, entities
---


title: Why can't I save a value from my form?

text:
# Question
Title: Why can't I save a value from my form?
I have a problem with my module that only creates a form to submit a validation. The target of this module is to set a variable that I put in a textfield. The problem is that it doesn't save the variable, it only shows the default value. (I use variable\_set and variable\_get)

This variable is necessary because I use this form in another module that get this variable from the database. (My variable is id\_event)

This is my code of my own module:

```
<?php
function example_form_form1(){
    $form['id_event'] = array(
     '#type' => 'textfield',
     '#title' => t('Id Event'),
     '#required' => TRUE,
         '#value' => variable_get('id_event', 7), //Here is my dude
    );

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

function example_form_submit($form, $form_state){
    $id_event = $form_state['values']['id_event'];
        variable_set('id_event', $id_event);//here is my dude
        drupal_set_message($id_event);
}
?>

```

Now, this variable is necesary for other module that only get.

```
<?php
$file_json = $this->options['xml_file'].variable_get('id_event', 1);
//Here don't get the value that i put, only put the value for default.
?>

```

Thanks :D

# Answer
> 3 votes
There are a few problems I see.

1. The submit function in this example doesn't follow the same naming
convention as your form constructor.
2. You are also setting the #value of the id\_event form element when you probably want to be setting the #default\_value (a #value cannot be changed by the user).
3. Your functions are missing their default arguments, which doesn't necessarily mean they will break but is bar form.

Try this:

```
<?php

function example_form_form1($form, &$form_state) {
  $form['id_event'] = array(
    '#type' => 'textfield',
    '#title' => t('Id Event'),
    '#required' => TRUE,
    '#default_value' => variable_get('id_event', 7),
  );

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

function example_form_form1_submit(&$form, &$form_state) {
  variable_set('id_event', $form_state['values']['id_event']);
  drupal_set_message($id_event);
}
?>

```

# Answer
> 3 votes
The reason your current code isn't working is because your submit handler doesn't follow the correct naming convention (i.e. FORM\_FUNCTION\_NAME\_submit) and you don't explicitly attach the submit handler to the form anywhere so it's not being run.

You can solve this by simply changing the nameof your submit handler:

```
function example_form_form1_submit($form, $form_state){

```

Or you could look at `system_settings_form()` which automates much of this process for you.

---
Tags: forms
---


title: drupal_add_js in html template file

text:
# Question
Title: drupal_add_js in html template file
I am using a zen subtheme and I am trying to add some javascript using the drupal\_add\_js on a certain node. When I use the drupal\_add\_js from within the **html--node--XX.tpl.php** file, it does not work.

But when I use it in the **page--node--XX.tpl.php** it does. I don't understand what causes the difference in the behavior. I thought that this would be the same. These are the lines I am adding in both cases:

```
drupal_add_css("sites/all/libraries/shadowbox/shadowbox.css", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("sites/all/libraries/shadowbox/shadowbox.js", array('type' => 'file', 'scope' => 'header', 'weight' => 5));
drupal_add_js("Shadowbox.init({skipSetup: true});", array('type' => 'inline', 'scope' => 'header', 'weight' => 6));

```

Can anyone illuminate me here?

# Answer
Using `drupal_add_js` in a variant of the `html` template will never work, because the styles are printed in the `html` template. At the time you call `drupal_add_js` the variable containing the styles have already been created and you are too late to alter it with `drupal_add_js`.

The reason it works in `page` templates is that it is parsed before the `html` template so the variable containing the styles that is printed in the `html` template has not yet been generated.
> 8 votes

# Answer
You can try to insert the JS files by the preprocess function in your theme's template.php file:

Here goes an example:

```
function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

```

You can use an if() to validate the current path in the $variables in order to prevent the script to be loaded on every page.

To debug the $variables values you can install the devel module an use the dpm() function.

For example:

```
function MYTHEME_preprocess_page(&$variables) {
  dpm($variables);
}

```
> 10 votes

# Answer
Structure is
html.tpl.php
-\>page.tpl.php
--\>node.tpl.php

So it is like html--page--node(--XX).tpl.php

Simply use node--XX.tpl.php but make sure there is a html.tpl.php, page.tpl.php and node.tpl.php file in your subthemes directory.
> 1 votes

# Answer
If you are looking to add javascript to individual nodes the best option is Code Per Node
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Is it possible to run Drush without root?
I run a Linux server that is administered by a friend of mine, and at the moment I work with Filezilla.

I've heard that Drush is a trivial installation: it seems to require no configuration and work out of the box.

However, it looks for configuration in several places:

> Drush installation directory, the home directory (as .drushrc.php), root directory of a Drupal installation, and site directory of a Drupal installation. Since the configuration files are just PHP scripts, they can contain any PHP code that you would like to have executed on startup of Drush. one could for instance call ini\_set() to set the value of a PHP configuration option.

and the configuration file /opt/drush/drushrc.php with following content:

```
# Allow Drush to use 128 MB of memory. Use -1 for no limit. ini_set('memory_limit', '128M');

```

I see this is necessary because PHP's default is too low, but I'm not sure if I need higher-level privileges because of it.

Do I have to have root-level permissions on the server, or am I able to work with Drush without them?

**Update:** As far as i understand this, i only have to ask my admin to get some more privileges (permissions)Note according to BetaRides answer i need to have more than only the access-data that the FileZilla needs - that are provided for the filezilla! Guess so - but i don not need root-permissions.

**btw** \- i have **secure-shell-access** (ssh2 access) guess that this is enough -With that i can setup a sftp-connection to the server with filezilla just lemme know - if i can use the exactly same data for the shell access (with the command line tool=?!=

# Answer
> 1 votes
If you need to change php.ini settings w/out root access, put either a php.ini or a drush.ini file in your $HOME/.drush folder. See http://drupalcode.org/project/drush.git/blob/HEAD:/README.txt

# Answer
> 4 votes
You do not need root-level permissions to use Drush: it'll work as long as the user invoking it has direct access to the Drupal installation directory.

Having the the same filesystem permissions as the web user should be enough for most operations: but for things like downloading modules, you'll need write-level access to the Drupal directory as well.

---
Tags: users, drush
---


# Question
Title: How do I add code to browse for a file in a Drupal Form?
I am trying to add items to a form (in code) similar to the add image item in the Drupal Add Content form that has the Browse and Upload buttons. In Firefox, the Browse button invokes a Pop-up window to search files on the user's computer and returns the selected file & path to the associated text box. I would like to review the code in Drupal to understand and duplicate the action. Thus far I cannot locate the code in core modules (its big in there and a file search does not find the word "Browse"!). Does anyone know where the add content form is, or a reference site that explains it, or how to code it?

# Answer
I recently created a few custom blocks with image upload and preview fields. Here's the relevant code that should be helpful for you:

```
function mymodule_block_configure($delta = '') {
  // Uploaded image path is saved in a variable.
  $pic_path = variable_get('mymodule_pic1', FALSE);
  $form = array();
  if ($pic_path) {
    $form['preview'] = array(
      '#markup' => '<img src="'. image_style_url('mymodule_img_preview_style', $pic_path) .'" alt="'.t('Preview').'" />',
    );
  }
  // Image upload field.
  $form['image'] = array(
    '#type' => 'file',
    '#title' => t('Upload image from your computer'),
    '#description' => t('Allowed extensions: jpeg, jpg, png, gif'),
  );
  return $form;
}

function mymodule_block_save($delta = '', $edit = array()) {
  // Functionality to validate and save the file.
  $validators = array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg'));
  $file = file_save_upload('image', $validators, file_build_uri('mymodule_images'), FILE_EXISTS_REPLACE);
  if ($file) {
    $file->status |= FILE_STATUS_PERMANENT;
    $file = file_save($file);
    variable_set('mymodule_pic1', $file->destination);
  }
}

```
> 1 votes

# Answer
The functionality you're referring to is built into Firefox (and all other browsers) so you won't be able to find the code in the Drupal code base. It occurs whenever you use `<input type="file"/>`.

In order to get that functionality in your forms use the `$form['image']` code that Dooshta provided.
> 1 votes

# Answer
If you are running Drupal 6, you need the Imagefield module (http://drupal.org/project/imagefield) but if running Drupal 7, it's already part of the core Content Construction Kit (CCK). To use it in either case, just create a content type with an image field and when you then create that content, it will bring up what you're used to seeing, eg, that browser form, when you input that field.
> 0 votes

---
Tags: 7, files
---


title: Programmatically delete CCK field value

text:
# Question
Title: Programmatically delete CCK field value
I have content type with Photos ImageField. I need to create some moderation view to show all photos and "delete" link to delete appropriate photo. How can I programmatically delete value from CCK field (in general not only ImageField but any field type)?

# Answer
> 1 votes
You will need to check the ImageField array to see what needs to be changed but for D6 but it should be something like the below:

```
$node = node_load($nid);
$node->field_photo[0]['value'] = NULL;
node_save($node);

```

Just change the field name to what you are using and change the $nid to the node id #.

# Answer
> 0 votes
WestieUK has a correct general expression. However, the vague question presents two potential cases for Filefield/Imagefield here:

1. Delete all references to that file from all nodes -\> `filefield_file_delete($file);`.
2. Delete only that node's reference to the file -\> Use WestieUK's method.

If there never are multiple node associations for the files in your structure (usual behavior in Filefield/Imagefield), method #1 is safe and simple to use for case #2 as well.
If the file is no longer referenced, do not forget to also remove the entry from the file tables and delete the file from disk with `file_delete($path);`.

---
Tags: 6, entities
---


title: restrict login access by IP

text:
# Question
Title: restrict login access by IP
Is it possible to restrict the login or role access by IP in drupal 7.Is there any module available in drupal 7 to provide similar functionality **Restrict Login** Any one guide me do this.

Thanks

# Answer
> 1 votes
I don't know of a module for Drupal 7.

However, you can add your IP check by implementing hook\_form\_alter for the login form. Just add a validate call back for your IP. See this post about some more information about hook\_form\_alter.

# Answer
> 3 votes
Check out the Restrict IP module.

> This module allows administrators to restrict access to the site to an administrator defined set of IP addresses. Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page with the message "Your address is not in the list of allowed IP addresses". No blocks will be rendered, and no JavaScript will be added to the page. This will happen for any and all pages these users try to access. The module also has various configuration options to whitelist or blacklist pages, bypass IP checking by role, and alter the output when the user is blocked.

---
Tags: 7, users
---


title: My images paths contains NULL

text:
# Question
Title: My images paths contains NULL
I have this content type called "Product" that contains a "Multimedia asset" field (Media module), called Images. Everything is working (I can access the image), except all my upload images have "null" in their path,e.g. "mydomain.com/sites/all/files/null/product-928.jpg."

The same happens when the image is rendered with a image style; in that case the path is "mydomain.com/sites/all/files/styles/table\_icon/public/null/product-928.jpg."

("table\_icon" is the name of my image style.)

I am using Drupal 7.10 and the Media module 7.x-1.0-rc2.

Do you have any idea on how to solve this problem?

Thanks!

# Answer
This is a known bug with the media module. See Issue #1351890: Wrong upload destination folder "null" and Issue #1364676: Upload path. The latter of the two contains a patch to fix this.
> 3 votes

---
Tags: media, uri
---


title: Logging out issue

text:
# Question
Title: Logging out issue
How can i prevent users who have logged out from accessing their account when they try to access their account by clicking the browser previous-page button?

Currently, users can access their previous session by simply clicking the previous page button. how can i prevent this, thus, they get redirected to the log in form/page?

# Answer
> 1 votes
Others have already mentioned that this is a caching issue, not a Drupal issue. Two thoughts:

1. Blocking the 'back' viewing of previous pages would conceptually be possible if the cached page (The one you clicked 'logout' on) contains Javascript that checks if the back button was pressed to arrive at that page. If 'Yes', then force a refresh or check for active credentials before allowing the display.
2. If you set appropriate Cache-Control headers and always generate an EXPIRED time in the past (example here) on all pages that display the 'logout' link, you can control this behavior in browsers that choose to comply.

Method #1 seems complex and could be impossible. #2 might be a 'best fit' but certainly not bulletproof. I would weigh the effort that is required to continue down this road against the overall concern you have of client machines storing cached pages.

# Answer
> 2 votes
There's nothing that can be done to correct this, it's a browser caching issue. When you hit the back button, it loads the original HTML from the cache, not the modified HTML.

---
Tags: 7, sessions, users
---


# Question
Title: Error reindexing attachments in Drupal 7 using Apache Solr Attachments module
I've installed Solr 3.4.0 and Tika .10 on my Windows 2003/IIS6 server. I have loaded the Apache Solr Attachments module and configured so I can search on documents attached to pages in my Drupal 7 web site. When I reindex on the Apache Solr search configuration page I'm getting 5 of these notices:

Notice: Undefined index: filepath in apachesolr\_attachments\_add\_documents() (line 133 of W:\www\drupal-7.8\sites\all\modules\apachesolr\_attachments\apachesolr\_attachments.index.inc).

The search index page indicates the attachments have been submitted for reindexing (message on the page -\> "There are 0 items remaining to be examined for attachments out of 23 total. The search index is generated by running cron. 100% of the site content has been sent to the server. There are 0 items left to send. " and "Number of documents in index: 23 (0 sent but not yet processed)"). On the Search settings page I see "100% of the site has been indexed. There are 0 items left to index." under Indexing Status.

Search is working for web site content but search for content in attachments is not working. If I got into Solr admin and query I can see web site content but searches for words in attachments return no results. So the attachments are not getting into Solr. Any ideas about what this error means or how I can debug it?

# Answer
> 1 votes
So I figured this out in case anybody else runs into this issue.

In the 7.x-1.x version of Apache Solr Attachments, there is a line of code in apachesolr\_attachments.index.inc that uses the PHP function `mb_detect_encoding`. That command relies on the PHP EXIF extension being installed and it is not by default. Once I modified my PHP installation to include it, it was able to process the files. I ran into some other issues though but finally got it all working. Details are posted here -\> http://drupal.org/node/1377416

---
Tags: search
---


# Question
Title: How can I check I run the Commons profile?
Yesterday I installed Drupal Commons on http://campus-24.com/. The version was grabbed from http://commons.acquia.com/home, but I am not very sure I have chosen the Drupal Commons installation profile.

In general the installation ends up with the appearance of exactly the same theme that is shown on http://commons.acquia.com/home.

It is pretty interesting that the above mentioned site does not feel/look, and it does not behave as a Commons. In short: The look and feel, and the behavior of the site is totally neurotic! If I look in the administrative area, I have only the following 6 themes in the system to choose between:

* Bluemarine
* Chameleon
* Marvin
* Garland
* Minnelli
* Pushbutton

So I guess there isn't a clear evidence that I have installed the wrong profile, the Drupal standalone installation profile, and not the Commons profile. Where can I have a closer look at which profile is active?

# Answer
The profile used to install the site is stored in the variable `install_profile`. There's a few different ways you can see the value:

* Pop into the `variable` table in your database and search for `install_profile`:

```
select value from variable where name='install_profile';

```
* Install the Devel module and visit `mysite.com/devel/variable`
* Put this custom code in a template file somewhere:

```
<?php print variable_get('install_profile', 'No install profile found.'); ?>

```

Hope that helps
> 3 votes

---
Tags: 7, distributions
---


title: hook_menu() (edit) not working

text:
# Question
Title: hook_menu() (edit) not working
I am doing something wrong and am not able to find what.

I have defined the hook\_menu for my module, add and delete are working fine, but edit and view are not. Is like are never being called.

```
function nutrition_menu()
{
  $items['admin/structure/ingredients'] = array(
    'title' => 'Manage Ingredients.',
    'description' => 'Manage Ingredients.',
    'access arguments' => array('administer ingredients'),
  );

  $items['ingredient/%ingredient'] = array(
    'title callback' => 'ingredient_page_title',
    'title arguments' => array(1),
    'page callback' => 'ingredient_page_view',
    'page arguments' => array(1),
    'access arguments' => array('view ingredients'),
    'type' => MENU_CALLBACK,

  );

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

  );

  $items['ingredient/%ingredient/edit'] = array(
    'title' => 'Edit',
    'page callbacks' => 'ingredient_page_edit',
    'page arguments' => array(1),
    'access arguments' => array('update ingredients'),
    'weight' => 2,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,

  );

  $items['ingredient/add'] = array(
    'title' => 'Add new Ingredient:',
    'page callback' => 'ingredient_add',
    'access arguments' => array('create ingredients'),
    'weight' => 1,
    'menu_name' => 'management',
    'file' => 'ingredient.pages.inc',
  );

  $items['ingredient/%ingredient/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ingredient_delete_confirm',1),
    'access arguments' => array('delete ingredients'),
    'weight' => 1,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,

  );

  return $items;
}

```

load functions

```
function ingredient_load( $iid = NULL, $reset = NULL)
{
  $iids = (isset($iid) ? array($iid) : array() );
  $conditions = array();
  $ingredient = ingredient_load_multiple($iids, $conditions, $reset);
  return $ingredient ? reset($ingredient) : FALSE;
}

function ingredient_load_multiple($iids=array(),$conditions=array(),$reset=FALSE)
{
  return entity_load('ingredient', $iids, $conditions, $reset);
}

```

Callbacks

```
function ingredient_page_view($ingredient,$view_mode='full')
{
  $ingredient->content = array();

  field_attach_prepare_view('ingredient', array($ingredient->iid=>$ingredient),$view_mode);
  entity_prepare_view('ingredient',array($ingredient->iid=>$ingredient));
  $ingredient->content += field_attach_view('ingredient',$ingredient,$view_mode);

  return $ingredient->content;
}

function ingredient_page_edit($ingredient)
{
  var_dump($ingredient);

  drupal_set_title(t('Edit @name', array('@name' => $ingredient->name)), PASS_THROUGH);

  return drupal_get_form('ingredient_form',$ingredient);
}

```

Basically what I see is the two tabs ( View, Edit ) with no information bellow, the title isn't changing either.

Any idea?

# Answer
The 'edit' page probably isn't working because you've mis-spelled `page callback` (it's currently spelt `page callbacks`).
> 3 votes

---
Tags: 7, routes, hooks
---


# Question
Title: Installing TinyMCE plugins on Drupal 7 with the WYSIWYG module
I using Drupal 7 and the WYSIWYG module and the TinyMCE (3.4.2) plugin. I want to install a plugin for TinyMCE.

I placed the plugin folder in the right directory.

```
sites/all/libraries/tinymce/jscripts/tiny_mce/plugins

```

However, the plugin doesn't show up in my configuration checkboxes for the WYSIWYG configuration. What else do I need to do to enable a contributed plugin?

# Answer
You need to inform the WYSIWYG module that you've installed a plugin, it won't know it's there otherwise. It will involve writing a small custom module.

Have a look in the `wysiwyg.api.php` and `wysiwyg.api.js` files included in the root of the WYSIWYG module folder; there are examples and very good documentation explaining exactly what you need to do.

The most important (perhaps only) hook you'll need to implement is `hook_wysiwyg_plugin()`
> 5 votes

---
Tags: 7, wysiwyg
---


title: Attach Fields to Entity during install?

text:
# Question
Title: Attach Fields to Entity during install?
How can I automatically attach/create fields to an entity when I enable a module that provides entities?

For example, I want my Entity to have an Image field, and a handful of text, date, and number fields ready to roll.

I see field\_create\_field and field\_create\_instance, do I need to define them or can I use whats already defined as fields in Drupal and just give them labels and default values?

# Answer
> 2 votes
`field_create_field` creates a field definition, and `field_create_instance` creates an instance of that field.

If you look at the UI, you are able to reuse the same field different places, this is what `field_create_instance` does.

Both functions requires an array with a lot of data containing info about which entity to attach the field on, labels various settings, how the field should be displayed etc.

# Answer
> 4 votes
This is a just a follow up to @googletorp's answer, you can use the following code to export an existing field instance definition to PHP code which you can then alter as you need to for your new instance:

```
$entity_type = 'node';
$field_name = 'field_name';
$bundle_name = 'node_type';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

```

That will give you both the `field_create_field` and `field_create_instance` code for the field.

# Answer
> 1 votes
I always solve this by creating the appropriate entity configuration in an install, exporting it with Features, and then make the install profile depend on it. As googletorp points out, manually creating a field requires a lot of data, and your bound to mess it up quite a few times if you write it all manually.

Even if you don't want to use Features for storing the field, you could still export them that way, and then copy paste the code into your own module.

---
Tags: 7, entities
---


# Question
Title: Using a node reference in Drupal 7, is there a way to tell what the parent node is?
I have a content type called Movie, it has a node reference to a content type called LeadActor. The LeadActor content type can have node references of its own back to several different Movies nodes.

When I have a page that displays the full content of a Movie, I've changed the node template to have a link to the LeadActor.

When a user uses the link to LeadActor from a Movie page, is there anyway for me to know what Movie the user came from when I'm on the LeadActor page?

I've thought about adding an extra argument to the LeadActor page link - the node id to the Movie, but I was wondering if there might be a cleaner way to handle this.

I'm using Drupal 7 and the node reference (references) module. I've also tried using the corresponding node references module - but so far I haven't been able to understand if this will work.

Thanks for your help.

# Answer
Reading the text of your question, it looks like you don't necessarily need to know what the parent is but more where the visitor is coming from (and if it is a movie which one).

A possible solution, as you mentioned, would be to add some parameters to the URL. A simpler option might be just a tiny bit 'o javascript.

```
<script type="text/javascript">
  (function ($) {
    $(document).ready(function() {
      var referrer =  document.referrer;
    });
  })(jQuery);
</script>

```

Then use the referrer (previously browsed URL) and compare it against the list of movie URLs via JQuery. If one matches, add a css class to style the link as an indicator.

```
<script type="text/javascript">
  (function ($) {
    $(document).ready(function() {
      var referrer = document.referrer;
      $('#movie-list li a').each(function(index) {
        if ($(this).attr('href') == referrer) {
          $(this).addClass("active-movie");
        }
      });
    });
  })(jQuery);
</script>

```

Where

```
<ul id="movie-list">
  <li><a href="http://example.com/duck">duck</a></li>
  <li><a href="http://example.com/duck">duck</a></li>
  <li><a href="http://example.com/goose">goose</a></li>
</ul>

```
> 1 votes

# Answer
There is a module called reference from URL it can help But I think you need only to know which album so send nid as an argument with the link "Change the node tpl of albums to add nid to the link" then in artist check args() to get nid
> 0 votes

---
Tags: nodes
---


# Question
Title: Which view do I have to use to make the order of the images random in Node Gallery Slideshow?
I'm currently using Node Gallery Slideshow module for displaying a gallery with a slideshow. It works correctly, but when displaying the images, the order of them is sequential, and I haven't found a way to make it random - at least on the admin interface...
So which view do I have to use to get a random order.

Thanks!

# Answer
> 2 votes
Under admin/build/views/list, look for node\_gallery\_gallery\_image\_views. Your probably looking for the 'view all image thumbnails' display here to have it randomize a full gallery. The current display order is based on your node gallery image weight so you'll want to remove these under 'Sort Criteria' (click the up down arrow icon to remove these settings).

After that, you want to add a sort order criteria, 'Global: Random' to have the results of the view sorted randomly.

Note: this will apply to all of your galleries since it is accepting an argument of the parent gallery node object. If you want this just to apply to one specific node\_gallery, you'll need to clone the display first and adjust this argument.

---
Tags: views, 6, media
---


# Question
Title: How do I add a custom template to my feature?
I have a feature with a few views. How to I add a custom template file to it?

Edit: Based on sheena\_d and schnippy's suggestions, here is my entire .module code. (It is still not working)

```
<?php
/**
 * @file
 * Code for the Nigel Gallery feature.
 */

include_once('nigel_gallery.features.inc');

function nigel_gallery_init() {
  drupal_add_css(drupal_get_path('module', 'nigel_gallery') . '/nigel_gallery.css');
}

$theme_registry['template_file'] = array(
  'template' => drupal_get_path('module', 'nigel_gallery').'/templates/views-view--gallery-content.tpl.php',
  'type' => 'module',
);

```

# Answer
The following code added to your .module file should do the trick:

```
function nigel_gallery_theme_registry_alter(&$theme_registry) {
$theme_registry['views_view__gallery_content'] = array(
      'template' => drupal_get_path('module', 'nigel_gallery').'/templates/views-view--gallery-content.tpl.php',
      'type' => 'module',
    );
}

```

For more information, take a look at the documentation for hook\_theme\_registry\_alter().
> 0 votes

# Answer
For either content-type or views templates, you're going to need to manually add these to your features set since ctools exports doesn't handle these. In your features folder (ex. testfeature), you want to create a subfolder for templates:

```
/testfeature
    testfeatures.features.inc
    testfeatures.info
    testfeatures.module
    templates/

```

and then copy all of your custom templates into this folder. Then in the testfeatures.module folder, you just need to use hook\_theme\_registry\_alter to add your content-type templates in:

```
function testfeatures_theme_registry_alter(&$theme_registry) {
    $theme_registry['template-file']['path'] = drupal_get_path('module', 'my_feature')."/templates/";
}

```

For views templates, you should have more success using a hook\_theme function, ex:

```
/**
 * Implements hook_theme().
 */
function nigel_gallery_theme() {
  return array(
    'views-view--gallery-content' => array(
      'variables' => array('view' => NULL, 'options' => NULL, 'row' => NULL),
      'template' => ' views-view--gallery-content',
      'path' => drupal_get_path('module', 'nigel_gallery'),
    ),
  );
}

```
> 0 votes

---
Tags: 7, theming, features
---


# Question
Title: Fetch images across the internet with File API
How can I use the FileAPI to fetch an image from another website via URL, and bring it into Drupal? Here is what I tried:

```
foreach ($data['photos'] as $item) {
            $photo = file_get_contents($item['url']);

            $filename = $entity->field_id['und'][0]['value'] . '-' . $x . '.jpg';

            $file = file_save_data($photo, 'public://' . $filename, FILE_EXISTS_REPLACE);

            if (is_object($file) && file_exists($file->uri)) {
                $file->status = 1;
                $file = file_save($file);
                drupal_write_record('file_usage', $file);
                $entity->field_entity_image['und'][] = (array) $file;
                $x++;
            } else {
                // error
            }
        }

```

It doesn't quite work. The first time around it grabs some of the photos, then the second time around, it should remove any photos in the system and resave them (even if none changed), I have no way to tell if the remote file is new or not.

# Answer
You might want to try just leaving the remote files as remote and have something like http://drupal.org/project/remote\_stream\_wrapper? There's an open issue in the module to add a field widget for image and file fields to support just a simple URL entry for a file.
> 3 votes

# Answer
Not quite what you are looking for, but I have used Imagecache External with decent results. Derivatives definitely gets saved locally. I don't 100% recall whether a copy of the original gets saved locally. This may or may not fit your needs.

The D7 version is in git, and not on the module page.
> 2 votes

---
Tags: 7, files
---


# Question
Title: looking for a slider module to use in the header
what's a good slider for a header in drupal 7 (I would like to have a slider for different content in other blocks/pages of the website, so if the same module could work for both, better)

# Answer
Try Views Slideshow. It is the most used and most flexible and you can create as many as you need.
> 2 votes

# Answer
There is an awesome slider for featured content in the header called Flow Slider. It's not integrated into drupal but it is very easy to use.
> -1 votes

---
Tags: 7, javascript
---


# Question
Title: Using views arguments to highlight/alter corresponding entries instead of filtering
So, I am making a tree based tab style menu for a section of my site.

There are 3 content types with node references going up the tree. They are ordered: Section \< Product \< Package.

If I am on a package I want to display 3 tiers of tab at the top of the page, filtered by the section/product the package is in and with the section+product+package that the package is a child of highlighted.

eg: If I am looking at "SECTION1 PRODUCT2 PACKAGE3" it should display the tabs like this:

SECTION1 section2 section3

section1product1 SECTION1PRODUCT2 section1product3

section1product2package1 section1product2package2 SECTION1PRODUCT2PACKAGE3

with the capitalisation representing something akin to the "active"class in css

My URL aliases are formatted: `example.com/[sectionname]/[productname]/[packagename]`

Edit: Many paths have failed me thus far... Any generic advice welcome...

# Answer
Ended up just manually making a menu to display the same information... Surely there should be support for one of: node path aliases as arguments OR menu generation from nodereference tree OR menu generation from url aliases (ideally from only selected nodes) Alas i found none of the above. I feel gross for creating the menu manually but there seemed to be no other way. Thanks for checking this out...
> 0 votes

---
Tags: 6, nodes, views
---


# Question
Title: How to display something conditionally in template file depending on the current path
I would like to do on page.tpl.php conditionally depending on the current path. I'm using Auto Assign Role and have two paths for registration.

Reading this tutorial, as far as I've understood I can make a template file that overrides the registration page. However I would like to display different things on two deferent paths. How can I do this?

# Answer
You could just test the current URL with `$_SERVER['REQUEST_URI']`:

```
<?php if ($_SERVER['REQUEST_URI'] == '/registration-page-1') : ?>
<p>Display something.</p>
<?php elseif ($_SERVER['REQUEST_URI'] == '/registration-page-2') : ?>
<p>Display something else.</p>
<?php endif; ?>

```

It's not exactly an elegant solution (there are better, more structured ways) but it will do in a pinch.
> 0 votes

# Answer
Drupal core's template suggestions allow for naming page templates based on the path of the page. So, theoretically, if you had www.mysite.com/registration-a, then you could use the the page template name page--registration-a.tpl.php and so forth.

However, if this does not work, you can create a page preprocess function in your theme or module that adds some template suggestions based on the path. For example:

```
function THEME_NAME_preprocess_page(&$variables) {

 if($arg[0] == 'registration-a'){
 $variables['theme_hook_suggestions'][] =  'page__registration_a';
 }

 if($arg[0] == 'registration-b'){
 $variables['theme_hook_suggestions'][] =  'page__registration_b';
 }

}

```

this would allow you to use page--registration-a.tpl.php and page--registration-b.tpl.php, etc.

For reference, $arg is an array that contains the different parts of a URL, so if you had the path mysite.com/registration/customer, then `$arg[0]` would be 'registration' and `$arg[1]` would be 'customer'.
> 2 votes

# Answer
Use the hook\_theme() function. So you can display two types of templates for two types of URLs. Here is the example.

```
function MODULENAME_theme() {
  return array(
    'theme_name_1' => array(
      'arguments' => array('param' => NULL),
      'template' => 'TEMPLATE_NAME_1',
      ),
          'theme_name_2' => array(
      'arguments' => array('param' => NULL),
      'template' => 'TEMPLATE_NAME_2',
      ),
    );
}

function MODULENAME_menu() {
    $items = array();
    //Link to the test_module admin page:
    $items['URL1'] = array(
        'title' => 'Test Module',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('advance_test_form'),
        'type' => MENU_CALLBACK,
    );
    $items['URL1'] = array(
        'title' => t('Test Module test template'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('advance_test_form'),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

  return $items;
}

```

If the form having the same fields use single call back function and call the theme depends on URL. If form fields are different, use two different call back functions.

Using themes the code is the following one:

```
return theme('TEMPLATE_NAME_1',$var);

```
> 1 votes

---
Tags: 6, theming, users
---


title: Drupal Custom Comment Module

text:
# Question
Title: Drupal Custom Comment Module
I am trying to create my first module in drupal 6. I just need to add some new fields to the already existing comment form(comment module). Eg: City,Email and state fields.

I have created 2 files: 1. mmcomment.module 2. mmcomment.info

Used a function `hook_form_alter()` like this:

```
 function mmcomment_form_alter(&$form, $form_state, $form_id) { // form override
 if ($form_id == 'comment_form') {
    // unset the other field elements

    $form['subject'] = array(
      '#access' => FALSE
    );
    $form['comment_filter']['comment'] = array(
      '#access' => FALSE
    );
    // add field to all comments

    $form['Email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email Address'),
      '#maxlength' => 255,
      '#size' => 30,
      '#required' => 1,
      '#weight' => 1,
      '#default_value' => $email
    );
     $form['displayName'] = array(
      '#type' => 'textfield',
      '#title' => t('Display Name'),
      '#maxlength' => 255,
      '#size' => 30,
      '#weight' => 2,
      '#default_value' => $displayName
    );

    $form['_author'] = array(
      '#access' => FALSE
    );
    $form['author'] = array(
      '#access' => FALSE
    );

```

I need to get the form values and insert into DB. What Function can I use for the same. I have tried: hook\_nodeapi(mmcomment\_nodeapi). But can't get the form values. Any suggestions.. Thanks

# Answer
In the `$form` structure you have to add/override the submit (and maybe the validate) handler.
> 1 votes

---
Tags: 6, forms, comments
---


# Question
Title: How to place custom module template file in theme folder
I am using Drupal 6, and I have created a custom module which is in the "sites\all\modules\custom" folder; in the same folder there is also the custom.tpl.php file.

I want to place the custom.tpl.php file in the theme folder.

Here is my code:

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

  $items['custom'] = array(
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_page() {
  $result = db_query('SELECT * from node');
  return theme('custom', array('output' => $result));
}

function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
      'template' => 'custom',
     ),
  );
}

function template_preprocess_custom(&$variables) {}

```

# Answer
Well you can place in the theme folder or you can leave it in the module. Drupal will look in both places. So if your implementation of `hook_theme` is a template, Drupal will look for the following files:

* `themes/bluemarine/custom.tpl.php`
* `modules/custom/custom.tpl.php`

If you read the documentation for `hook_theme` you'll get your answer for the question when you get to the **path** key:

> path: \[...\] *Ordinarily the **module or theme path** will be used* \[...\]
> 1 votes

# Answer
Please give path key in theme registry.

```
function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
       template' =>  path_to_theme() . '/custom',
      'path' => '/'
     ),
  );
}

```
> -1 votes

---
Tags: theming
---


# Question
Title: How to rewrite View SQL query to bypass MySQL query cache (SELECT SQL_NO_CACHE)
I would like my View not to use MySQL cache as one of the checks in WHERE clause keeps changing with current time (granularity set to second). Caching this query doesn't make much sense. I would like to convey this to MySQL server by rewriting SQL to `SELECT SQL_NO_CACHE`. I looked at `hook_views_query_alter(&$view, &$query)` with a hope to achieve it but I couldn't figure out how `$query` need to be altered for this. Usecases found so far talks only about changing order by and where clause conditions. Any directions pertaining to this will be greatly appreciated. Thanks in advance.

# Answer
I don't want to say that this is impossible, but it's very close to be true.

The problem is that Views uses the Drupal SQL builder, so when making a select query, it utilizes the `SelectQuery` which again uses PDO from PHP. PDO can be used in two ways, either you feed it a query, or you can use it to build a query by instantiating the class and dosing stuff like

```
$query = ...;
$query->addField(...);
$query->addCondition(...);
$result = $query->execute();

```

The challenge is that you need to tell PDO that you don't want to make a regular `SELECT` query but instead an `SELECT SQL_NO_CACHE` query. I don't know if that is possible of how you would do it if it were. Even if it is possible, you still need to figure out how to do it through all the abstractions of classes created by PDO and Drupal and Views.

Drupal has a hook you can use to alter queries in general which probably will be the easiest route if you can figure out the above: `hook_query_alter`, alternatively you can subclass `views_plugin_query_default` defined in Views, where you can add alter how the query is created to add `SQL_NO_CACHE`. Again PDO and abstractions is the challenge.

If you are using Drupal 6 this should be more simple and you can probably use something like `hook_db_rewrite_sql`.
> 2 votes

---
Tags: caching, views
---


# Question
Title: Drupal 7 - can't uninstall Features module
i just started to mess up with Drupal 7 (and Drupal in general sense) - and i can't uninstall module named Features it gives error

```
PDOException: SQLSTATE[HY000]: General error: 1 no such table: menu_custom: DELETE FROM {menu_custom} WHERE (menu_name = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => features ) in features_uninstall() (line 29 of /Users/umren/projects/LAMP/sites/all/modules/features/features.install).

```

p.s. i'm using sqlite if it matters

# Answer
You are missing the `menu_custom` table which is defined by the menu module. Most likely the problem is dependencies. If you install the menu module, that should fix it. If the menu module is already installed, the problem is that your database is broken.
> 2 votes

---
Tags: 7, features
---


# Question
Title: Can theme function be implemented in a module file?
For example, in bartik theme, it has

```
/**
 * Implements theme_menu_tree().
 */
function bartik_menu_tree($variables) {
  return '<ul class="menu clearfix">' . $variables['tree'] . '</ul>';
}

```

Is there a way to override it via .module file?

# Answer
Modules can create the initial implementation of a theme function but they can't override existing theme functions.

Modules do have one option available which should be used as a last resort: `hook_theme_registry_alter`. I would advise against every using this, since it will lead to code that's harder to maintain, and make it hard on those needing to theme the site. Also modules should be design never worry about theme functions of other modules, that is why we have themes. With that being said, if you change the theme registry you can change which function will be used regardless of what is normal practice, meaning that you will overwrite functions defined in themes. You can however use logic to prevent that from happening, but it can easily lead to many WTF moments, especially 6-12 months from now when you or some one else need to maintain the site.
> 9 votes

---
Tags: theming
---


# Question
Title: How do I override a fields output in a Views template?
I have a field, foo, set to "Exclude from display", and output later in a "Global: Custom text".

I need to control the rendering of this field based on a different value on the same node. I thought I could just implement a template file like:

```
function THEME_views_view_field__VIEWNAME__DISPLAYNAME__FIELDNAME($view, $field, $row) {
  $output = isset($bar) ? $foo : $baz;
  return $output;
}

```

But as soon as I add this function to my template.php file, I loose *all* output instead. No matter what I return, I get nothing. I tried trivial things like

```
return 'AAAAA';

```

to no avail. I'm probably doing something very simple wrong, but looking at my own previous attempts to do similar things in the same template file, I can't see what's wrong. Yes, I've cleared the cache numerous times.

# Answer
> 0 votes
I thought that I was doing something fundamentally wrong here, and my question was generally asking "How do I do this right". I'm not what changed, but simply messing with a few Views settings and reverting them, fixed the issue. My best guess is that at some point, Views accidentally saved "bad" data, which caused it not to pick up the right templates.

I was recommended by a moderator to accept this as my own answer, but I will up-vote the others, as all suggestions were helpful. :)

# Answer
> 2 votes
I don't know if this is the answer you wanted, but I template the individual fields by templating the custom:global, and accessing the individual pieces through the `$view` object.

# Answer
> 1 votes
Is that in your template.php? Why not just override the tpl.php file being used to generate the output and do it there.

# Answer
> 1 votes
If you use Display suite module, you can write php code in "Global: Custom text". Perhaps, it will help you.

---
Tags: views, 6, theming
---


# Question
Title: Various View-panes with arguments from url in the same panel-page. It is possible?
I'm making a web about football and this is the situation of my problem:

I have a content-type called 'player stats' taxonomized with the vocabularies 'season' & 'day' and another content-type called 'chronicle' with the same tag-system of the 'player stats' content-type.

I want to have my custom node-template for all the content of type 'Chronicle', but including in any content-pane a Views-pane with content from the 'player stats' for a given 'season' and a given 'day'. My url structure is: example.com/chronicle/season-x/day-y and I tried to get arguments from url but the internal path node/% impossibilite it (as far I know)...

My second option is to create a Panel page, and try to insert content (using views pane's with contextual filters) from both content-types 'chronicle' and 'player stats' to make a chronicle with complete stats of the players in the same page. But my problem is that I only get visible ONE View-pane, the other ones seems not to work an I can't see any more view-panes that compose my panel-page. (please, see attached snapshots)

I am doing anything wrong? I'll glad to read you suggestions and your help. (sorry for my bad english, I'm catalonian from Barcelona). Thanks.

Attached files::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

It's my first time posting here, so I have not enough privilieges to attach more than 2 links. But snapshots & export-files are available in the original post, at drupal.org:

# Answer
This discussion has gotten long in the issue queue already, so instead of repeating what's been said there, I'm try to explain from scratch how you can have two Views in the same Page, with the same arguments.

1. Create two Views. In both Views, add *only* a single "Content pane" display. **No page displays**.
2. Configure your contextual filters on both content panes, make sure they expect the same type of argument.
3. In the pane-specific settings, set both panes to get their arguments from context, pick appropriate context objects.
4. Create a new custom page, or use an existing one. Add both content panes.
5. Done.

Additional comments: I guess the settings of both Views have more similarites than their arguments, so I would put both of the content panes into one View.
> 1 votes

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


# Question
Title: How to pass an argument into Views for Drupal 7?
I'm trying to pass an argument through a block created by a view.

The node is an ubercart product node. I have aliased the paths such as:

node/45 to products/\[name\]

In contextual filters, I've chosen the filter "Content: Nid"

In the Preview with contextual filters it works with the node id as it should. e.g. "45" but the view doesn't show on the page node/45.

I believe the alias may have caused the problem, but I thought Drupal was designed to have aliases converted to node id's.

# Answer
In your contextual filter, under **WHEN THE FILTER VALUE IS *NOT* AVAILABLE**, choose **Provide default value** and select "Content ID from URL" under **Type**.
> 12 votes

# Answer
You can also define an "Exception value" in the "Provide default value" option, like "all" which will bring you all the results.
> 1 votes

---
Tags: nodes, views
---


# Question
Title: How do I make a multi item table order list for Drupal Commerce?
I have several items that should be allowed to be ordered on one page using Drupal Commerce. Take the example of dairy products. There should be a table of dairy items a person can purchase such as milk, cream, butter, and cream cheese. Each of these items should be viewed as a row of a table in the dairy page. The customer should be able to mark the number of each item they want to purchase and submit the form using a purchase button at the bottom of the table. How is this done using Drupal Commerce? The checkout view does just this. Is it possible to create views that do this too?

Here is an image of the checkout form that does this.

# Answer
> 2 votes
I think you're looking for the Commerce Add to Cart Extras module. You can use this with Views to build your own lists of products and add multiple quantities of multiple products with one click.

---
Tags: commerce
---


# Question
Title: How can I create a view on a profile page that shows content related to the user we are viewing
I have a specific "sport user id" that the user provides in order to grab sports results about that user. I want to display their results, which I keep updated and organized programmatically in a cron job, on their profile. The way I would like to link the content would be by keeping the "sport user id" as a field in the result content type and also as a field in the user.

How do I go about creating a filter to do this?

# Answer
> 0 votes
Check out the EVA (Entity Views Attachment) module. This allows you to create views, which you can use as a field on any entity (node, profile, user or whatever) you like.

After you created the view, go to "Manage Display" of your content type and move the field in the right position.

# Answer
> 0 votes
This is a simple way to show content of a user on their profile page:

* create a view of the content with a contextual filter (called argument in D6) "userid from URL"
* assign the view to a block
* assign that block to show on the user profile (user/uid)

---
Tags: views
---


title: Override node title validation

text:
# Question
Title: Override node title validation
I have a pretty specific case where I want to fill in the node title myself if the user fills a checkbox above the title field.

For this reason, I can't use autonodetitle (because the title is only automatic if the checkbox is selected).

I have added my own validation callback using array\_unshift() in a hook\_form\_alter to make sure its the first one but when its called the form already has an error (title field is required)

Is there any way I hook into the validation process earlier or even just remove the error for this field?

Thanks!

# Answer
You can easily hook into the validation process by implementing `hook_form_alter(&$form, &$form_state, $form_id)` or it's cousin `hook_form_FORM_ID_alter()`. There you can inspect the `$form` variable, find out where the array of validation functions is, and perform `array_unshift()` on it.

You could also use the form alter hooks to modify the `#required` property of your title field, therefore preventing further validation errors down the line.

Don't forget that in order for your `array_unshift()` operation to be successful, the form needs to be passed by reference to your hook, or else you would only be modifying a local copy of the form variable. It's very easy to forget adding the ampersand `&` in front of `$form` in the hook implementation. i.e. ...`& $form`...
> 1 votes

---
Tags: 7, nodes, forms
---


# Question
Title: How do I get rid of the "Configure Blocks" link above my menus?
I know the answer to this will be obvious (and probably embarrassing), but the link started appearing on my new development site, and I want to turn it off to do some styling. The link only appears above menus and I cannot find a setting in a relevant module to turn it off. This problem is at the annoying stage for me, but could become an obsession if I..don't....squash.....this......nasty..........bug!

Does anyone know what controls this? :)

# Answer
> 3 votes
I think those links come from the core "Contextual links" module; you should be able to pop to `http://mysite.com/admin/modules`, disable the module and see the links disappear :)

A bit of extra info on Contextual Links:

http://drupal7ish.blogspot.com/2011/06/contextual-links.html

# Answer
> 2 votes
The Contextual Links core module controls these. Just turn that off and you're laughing!

---
Tags: 7, routes, navigation
---


# Question
Title: Print stylesheets & overriding a base theme style sheet
Since adding a print style sheet and marking the screen stylesheets accordingly:

```
stylesheets[screen][] = css/example.css

```

rather than

```
stylesheets[all][] = css/example.css

```

The Genesis base themes are overriding the similarly named site styles in my sub theme. Specifically /sites/all/themes/genesis/genesis/css/layout.css is overriding my sub-theme layout.css file.

I've tried adding 'fake' calls to empty stylesheets (as per 'Overriding style sheets from modules and base themes'), with no success:

```
;----------// Modular Stylesheets

; Stop base overrides with fake file
; http://drupal.org/node/225125#comment-3028740
; http://drupal.org/node/263967
stylesheets[all][] = css/base.css
stylesheets[all][] = css/layout.css
stylesheets[all][] = css/blocks.css
stylesheets[all][] = css/comments.css
stylesheets[all][] = css/nodes.css
stylesheets[all][] = css/page.css
stylesheets[all][] = css/style.css

; block, comment, node, page and style CSS.
stylesheets[screen][] = css/blocks.css
stylesheets[screen][] = css/comments.css
stylesheets[screen][] = css/nodes.css
stylesheets[screen][] = css/page.css
stylesheets[screen][] = css/style.css
stylesheets[screen][] = css/layout.css
stylesheets[screen][] = css/forms.css
stylesheets[screen][] = css/rows.css

; Print css
stylesheets[print][] = css/print.css

```

I think the issue is that the later \[screen\] type is included as an extra stylesheet, rather than overriding the first \[all\]. But I can't see a way round it ....

# Answer
> 1 votes
You shouldn't be doing

```
stylesheets[][] = ...

```

Instead you should be doing

```
stylesheets[type][] = ...

```

type is the type of media to include the stylesheet for, like all, screen etc.

# Answer
> 1 votes
Is it a problem to have both CSS stylesheets included? I guess not. screen and print will have similar CSS styles on some items.

So just override in your CSS stylesheet for 'print'... This way you don't have to override the whole CSS page.

Example: stylesheets\[all\]\[\] = css/style.css

```
H1 {
font: Georgia 0.9em;
color: red;
}

```

stylesheets\[print\]\[\] = css/print.css

```
H1 {
color: black;
}

```

Both CSS files are loaded, no problem. Font is used from the first stylesheet, but the color value is overridden in print.css...

---
Tags: theming
---


# Question
Title: display custom order fields in a checkout pane of drupal commerce
I have added a custom field in orders and I can view and edit. I want to display this custom field in checkout panes, so users can fill them. but by default there is no relation between fields that we can add to checkout panes and the fields that we add to orders.

How can I display fields that I add to orders in the checkout form?

# Answer
> 3 votes
Try Commerce Fieldgroup Panes module.

> This enables an easy way to collect information in the checkout process... The collected information is auto added to the order... You can watch a demo usage in Commerce module Tuesday videocast: http://www.commerceguys.com/resources/articles/257

---
Tags: commerce
---


# Question
Title: Find all contexts in which a block appears
Is there a quick way to find, for a particular block, all of the contexts that can display it?

# Answer
> 2 votes
You can quickly find all the contexts in which a block appears by performing a code search. Exported Contexts are placed inside `name_of_your_feature.context.inc` files. So when searching your Contexts for a particular block name you could restrict your search to `*.context.inc` files. Here's an example Zend Studio/Eclipse search as described above:

My team generally puts Features (which contain exportables such as Contexts) in their own dedicated folder, making your code search faster and more efficient.

```
/modules
  /contrib
  /custom
    /features

```

---
Tags: blocks, 7
---


# Question
Title: My Feature depends on a module. Do I have to specify that module's dependency, as well?
My Feature depends on Views. Views has a dependency on Ctools. Do I have to specify Ctools as a dependency in my feature as well.

# Answer
If you use ctools calls in your module, then you should declare it as a dependency. Otherwise no need.
> 1 votes

# Answer
As general advice, declare the dependency from the modules for which your module needs to access their functions, or classes.

In the specific case, even if you know that the Views module requires the Chaos tool suite module, and your module needs both, it is better to explicitly declare both as module's dependencies.
The difference is just a line more (`dependencies[] = ctools`) in the .info file, but that doesn't create problems to Drupal. Adding that line is also less error-prone: Suppose that your module doesn't depend from the Views module anymore; if you didn't have that line, and you don't add it, the module would not work correctly for who install it, as it would be enabled even if the Chaos tool suite module is not present. It also help if you are developing a version of that module for Drupal 6; in Drupal 6, the View module doesn't declare the Chaos tool suite module as dependency. If you declare just the dependency from the Views module your module would not work if it uses a function the Chaos tool suite module.

Similar thing can be said for modules that depend from Drupal core modules, which are required from Drupal itself. As Drupal 8 shown with the Node module, those modules could not be anymore required from Drupal, and there could be profiles where the Node module is not required. If a module depends from it, but it doesn't declare it as dependency, it would not work in Drupal 8 without to change its .info file.
> 1 votes

---
Tags: 7, features
---


# Question
Title: Pulling components out of a Features module into a Drupal site
I have a site that has some functionality provided by a Features module. They include a view, some nodes, and some content types. Now, we don't want them in the Feature anymore; we want them as native Drupal things.

How do we migrate components provided by a Feature module back into Drupal?

# Answer
Use the Feature Tools module. The main goal of the module is to give the ability to remove elements from a feature and put them back to the DB. It adds a "Safe Create Feature" button to the recreate feature form, that detects the element that has been removed from the feature and saves them in an unlink file. In order to save the elements to the DB you need to go to the admin/build/features/unlink page, check the element you need to import and submit.
> 2 votes

---
Tags: 7, features
---


title: block-[region].tpl.php is not working?

text:
# Question
Title: block-[region].tpl.php is not working?
I just created the **Blocks** and **Regions** in drupal 6. Now I want to align these regions (by using DIV id's etc..), so I created a block-\[region\].tpl.php file and write HTML and PHP scripts. Unfortunately these scripts are not showing in that regions, only the block contents are showing.

By the article, template files are searched in the following order:

* block-\[module\]-\[delta\].tpl.php
* block-\[module\].tpl.php
* **block-\[region\].tpl.php**
* block.tpl.php

But the contents in the files are not displaying. How I figure-out this problem ?

# Answer
> 2 votes
My best guess is that you haven't copied across the standard `block.tpl.php` file into your theme. This is required (for a reason that escapes me) for overriding node and block templates.

There's a bit of a discussion about it in the comments on the link you posted.

---
Tags: 6, blocks, theming
---


# Question
Title: Uploading changed Drupal content from production to server
I haven't yet setup version control (GIT) for my development and production environments as a result I am facing trouble syncing everything. My site is powered by Drupal 7.

For example, for a Content type that I created, what exactly is the folder on my development site that I should be uploading. And as far as the content type I created, what folder should I be uploading to the live server?

Another case is where I make changes to 'Text formats' found in admin -\> configuration and a couple of other places in admin -\> configuration, well, Not sure what folder I should be uploading either.

# Answer
> 0 votes
Use "Backup and Migrate" module or "Features" Module to upload your content to the production server.

# Answer
> 1 votes
GIT will not be helpfull in this case. To transfer a contenet type from one Drupal installation to an other one you can either export and import it or use the features module (with features GIT could be handy).

For the other configuration changes you might be succesfull with the strongarm module. But for small configuration changes it's often more convenient to take some notes and just redo them on production.

---
Tags: nodes, migrations
---


# Question
Title: Add Object in json file generate by services module drupal
I need some help about this problem. I need to add object that encompasses the hash of my json file.

I use services module in drupal 6 for generate xml and json file from my nodes. So, when i view my nodes in json i have this:

```
[
{
"nid": "7",
"vid": "7",
"type": "page",
"language": "",
"title": "Bievenido", ..... } ]

```

But i need that this json file look like this:

```
[
{
"<whatever>": {
    "nid": "7",
    "vid": "7",
    "type": "page",
    "language": "",
    "title": "Bievenido", .....  } ]

```

How to change this json file generated by services module?

# Answer
> 2 votes
The JSON is generated by the `RESTServerViewBuiltIn` class in the `services/servers/rest_server/includes/rest_server.views.inc` file, specifically the `render_json` member function.

Services does provide a way to override this.

Firstly in a custom module implement `hook_rest_server_response_formatters_alter` and change the View class that's used to render the output to a custom one:

```
function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['json']['view'] = 'RESTServerViewMYMODULE';
}

```

Then add your custom View class (I'd keep this in the module file to avoid having to load includes):

```
class RESTServerViewMYMODULE extends RESTServerView {
  public function render() {
    $new_data = new stdClass;
    $new_data->some_key = $this->model;

    $json = str_replace('\\/', '/', json_encode($new_data));

    return $json;
  }
}

```

Hope that helps

---
Tags: services, 8
---


# Question
Title: Is there a way to set the pager's page number programmatically without the page being in the url?
I would like a user who has previously left a comment on a node to initially see the last page of comments while a new user (to that node) will initially see the first page of comments.
I know that the page is controlled by the pager and is set by the "page" variable in the URL (`$_GET['page']`). Is there a way to set this programmatically?

(Just to clarify, I am not using the Views module on this project.)

# Answer
> 1 votes
You can use AJAX to call a new request so you will not have the page in the URL or, if you use Views, select "Use AJAX" under the Advanced Settings, and it will enable AJAX on your pager.

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


title: Error message when uploading an image

text:
# Question
Title: Error message when uploading an image
During Image upload, I get an 'Http error 0 occurred' when the file size is larger than the allowed maximum file size. Is this a correct behavior? and how would I provide a better error message. I have tried this in different browsers all show this message and changed settings in php ini file based on discussions on this topic.

Thanks for your help.

# Answer
> 1 votes
You're going to see this error when you try to upload an image file that PHP has an issue with, either because it is larger than the allowed maximum file size in PHP or because trying to process the image (ex. for creating thumbnails) is consuming more memory than you have allowed in your php.ini.

There is a *monster* thread on this topic over at Drupal.org but the key takeaways are to try and increase these two values (php file upload or memory limit) or to switch your imageapi library from PHP GD over to ImageMagick to avoid the memory constraints.

---
Tags: 6, media, ajax
---


# Question
Title: When should field_attach_load be called manually?
I'm trying to use the module ClosedQuestion together with EntityCache. When I enable EntityCache, then the fields on my CQ nodes becomes duplicated. I believe the cause is that both EntityCache, and ClosedQuestion, calls field\_attach\_load on the nodes.

There's a specific issue here, about this problem, but I'm looking for more general information, about what is the *intended* usage of field\_attach\_load? I've never seen a module doing it manually before, and don't think it's supposed to be used like this.

# Answer
api.drupal.org says:

> field\_attach\_load() is automatically called by the default entity controller class, and thus, in most cases, doesn't need to be explicitly called by the entity type module.

Basically only call it if you're implementing an entity type and don't want to use the default entity controller. I'm pretty sure ClosedQuestion is in the wrong, since it's only making a node type. All fields should be attached by the time `hook_load()` comes along.
> 1 votes

---
Tags: 7, caching, entities
---


title: Ubercart theming

text:
# Question
Title: Ubercart theming
I have added the Ubercart module to drupal 7 and I am having difficulty with the current theme of the items Ubercart uses. I can trace the stylesheets to the public\_html/sites/default/files/css folder. In this folder there are about 50 css stylesheets that look generated.

My issue is that the current colorschemes Ubercart is using on my site dont match. I need to edit the stylesheets but can't find specifically where to do so. The generated stylesheets with names like "css\_LRLsfsdfgsg.css" do not do the trick.

Has anyone encountered this or know where I can properly style ubercart to work with my drupal site??

# Answer
You need to turn off the css aggregation at admin/config/development/performance and then clear your cache. Then with firebug inspect the elements and then apply your own css overrides in your own theme or subtheme.
> 1 votes

---
Tags: ubercart, theming
---


title: View and CCK select list

text:
# Question
Title: View and CCK select list
i have created a content type in which i have a field with a select list. I create views for each option i have on the select list and am not sure how to go about it.

Example - Select list options - car, bicycle, motorcycle

View displaying all cars view displaying all bicycles view displaying all motorcycles

i Have tried using taxonomy but i keep getting ajax errors hence why i created a cck select list.

Thank you in advance.

# Answer
In a page view, add all of the fields you wish to display. Then add a filter in the Filter Criteria area that includes this field, then set the Operator to once specific selection (e.g. cars). Clone each page and override this filter for each page to filter for the other selections. (You could also just create on page view and expose the filter for users to change it on the fly.)
> 2 votes

# Answer
Go to Add new view, give it a name, Show Content of type YOURCONTENTTYPE, Create a page = yes, give it a URL and then click continue and edit. Pick which fields you want shown (or full rendered entity etc) and display style (show as a grid, table etc). Add a filter criteria and choose the select list field (or taxonomy term if you want to go back to that way) and expose it. This will now give you a page (the url you chose) where users can click a dropdown list to get the list of items.

If you wanted to go back to using taxonomy you could easily do so without even touching views. Basically you would let the users choose a taxonomy term from the vocabulary and clicking that taxonomy link on the node page will go to a taxonomy listing all the nodes tagged with that term. If you want to use views to do the same you need to start using contextual filters and depth modifiers (see the default taxonomy view as an example).
> 2 votes

---
Tags: views
---


# Question
Title: Ways to implement auto voting feature on a content type?
I have a content type called "articles". A user adds a new article and other users on the site can vote for the article. I am using the Drupal default poll module. In order for this to work, I have to do the below steps:

1. Create new poll.
2. Link submitted article to newly created poll.
3. Publish article to open it up for voting.

I am trying to eliminate step 1 and step 2. In other words, the poll would immediately be registered into the newly submitted article. Aside from writing my own custom module, is there another way?

# Answer
The Rate might be useful for what you are trying to accomplish.

> This module provides flexible voting widgets for nodes and comments.
>
> Administrators can add multiple widgets. By default, there are 8 widget types to choose from:
>
> * Thumbs up
> * Thumbs up / down
> * Number up / down
> * Fivestar
> * Emotion (this makes me mad, angry...)
> * Yes/no
> * Slider (Drupal 6 only)
> * Custom
> 2 votes

---
Tags: 7, polls
---


title: Panels for Node Types

text:
# Question
Title: Panels for Node Types
I need to control the layout a particular, pre-existing node type using panels. However unless I'm not mistaken, creating a panel for a node type allows you to manipulate the layout for every node of that type, whereas what I want is a default panels layout - which I can change if I need to - but free reign over adding new content elements for each node I create (of that type).

I could override the nodes individually by entering the un-aliased path for each node, e.g node/123. However it's not very clean or intuitive, has to be done manually for each node, and I lose some useful information in my template pre-processing.

I could use the panels\_node module, but this creates a new node type called "Panel", and while what I want is similar, the node type already exists - and I'd need the option of creating a new node type that uses panels later.

...or am I missing something really obvious?

Any help would be appreciated.

(Drupal 7, Panels 3)

# Answer
> 5 votes
If I clearly understand your question You want to create something like this:

*Different layout based on Node Type*

1. Go to Structure --\> Pages and enable Node Template (/node/%node)
2. There should be only one variant - go to Selection Rule. From drop down menu choose Node Type: and then choose Variant for Node Type being viewed.
3. Create as many varants as you need for any Node Type

# Answer
> 0 votes
One option is to add noderef fields to your content type, which would point to the "extra" content that you want to add to each page. Your panel page would then have the node itself on it, and then a bunch of views to pull in the referenced content. We do this all the time for sidebar callouts.

# Answer
> 0 votes
This may not answer your question entirely since I'm not sure I understand it. Since you mention panel nodes, I want to point out that panel nodes, are being *deprecated*. You should not use that module, instead, you should take a look at Panelizer, which allows you to "Panelize" any node of a regular content type.

---
Tags: 7, panels
---


# Question
Title: Simplenews unsubscribe link shows a 404 Page
In my Newsletter the unsubscribe URL which is inserted by a token, returns a 404 page. The URL of my Link is:

http://www.mysite.info/newsletter/confirm/remove/

What could be the issue?

# Answer
There are many issue thread on simplenews about this issue.

Currently the only supported version of simplenews is version 6.x-1.3 (May 21st 2010). Most of the issues have patches that are commit to 6.x-2.x-dev and 6.x-2.0-alpha2. You might want to upgrade. If you don't, then you will need to apply one or multiple patches to fix your problem.
> 1 votes

# Answer
For the Simplenews module, the default is to provide a subscriber with an unsubscribe link when they receive an email from a posting i.e. creating of an issue. This process of appending the unsubscribe link is a default action of the module. The typical link which is appended to all sent newsletters includes the standard text, i.e. click here to unsubscribe.

The link provided to the user in the email is similar to

```
http://www.mysite.info/newsletter/confirm/remove/2210afaa624t1

```

... where the id at the end is the one linked to the email address when the user first subscribed.

If you don't include the ID on the URL, then you will get the 404 error.

I have not seen a feature that lets a user come to the site and enter an email address and then click a remove button. I'm guessing someone would have to add this as a module if desired.
> 0 votes

---
Tags: emails
---


# Question
Title: Adding links on top of view rotating banner
I am trying to add a link to a page (about us) on top of a view with a rotating banner. There are three banners and i only want the link to appear on top of one of them. Any suggestions?

# Answer
> 1 votes
Add a "Global: Text area" to the header of your view that includes the link. This way it will always appear.

---
Tags: views, navigation
---


title: Disable checkout button

text:
# Question
Title: Disable checkout button
I am using drupal 7 with ubercart. Since I do not currently have a method to accept credit cards, I am using paypal express. The issue I am finding is that still in the cart view there is a checkout button and a paypal button. If the user clicks the CHECKOUT button they are taken to the next page but can go no further since there are no Credit Card options currently enabled.

Is there a way to only show the PAYPAL button in the cart? If so where? I am not sure which file I should be looking in for the cart form.

# Answer
Go to admin/store/settings/checkout and disable checkout.
> 1 votes

---
Tags: 7, ubercart
---


# Question
Title: Get current region name in node template Drupal 7
I need to find out what region the node block is appearing in within the node template. I am using node block module to display nodes as blocks but need to know what region the node blocks are appearing in within the node.tpl. In Drupal 6 there was a template preprocess function where you could set a global var to accomplish this but that function is not available in D7. Thanks for any help.

It won't let me answer my question yet so I will put it here.

If anyone else runs into this and wants to know what region the node is being displayed in within the node template using the node block module or something like it. You can use the template\_preprocess\_node($vars) function and add the region to the content so that it will be in the content array in the node template like this.

$vars\['content'\]\['region'\]=$vars\['elements'\]\['#block'\]-\>region;

# Answer
If anyone else runs into this and wants to know what region the node is being displayed in within the node template using the node block module or something like it. You can use the template\_preprocess\_node($vars) function and add the region to the content so that it will be in the content array in the node template like this.

```
$vars['content']['region'] = $vars['elements']['#block']->region;

```
> 2 votes

# Answer
There is a variable for that: `$block->region`. This and other variables that are available inside the block template can be found inside the commented-out area (at the top of the template).
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: Views: Select nodes having a specific field empty
I know how to create a filter to show nodes having a specific field empty, using *Is equal to* operator, But I want to expose this filter to visitor in form of checkbox. I want a check box for example with title "Show nodes that doesn't have an image".

Is it possible using Views 3?

# Answer
> 2 votes
Have you tried using better exposed filters?

---
Tags: 7, views
---


# Question
Title: How can I provide an optional link to a Forum from a node (D7)?
I have custom node types 'foo' or 'bar', and each node should have its own associated forum you can easily navigate to from that node. I was hoping to eventually use the rules module to generate the forum upon 'foo' or 'bar' creation.

To both 'foo' and 'bar' I've added a custom Term reference field which is validated against the Forum taxonomy, and I have **not** marked the custom field as required. But when trying to save any of these content types, it's making this forum reference required. Why?

Possibly related - when I add this custom field to a pre-existing content type and then view a node of that type, I get the following error:

> Notice: Undefined property: stdClass::$forum\_tid in forum\_node\_view() (line 271 of modules/forum/forum.module).

And if I try to edit, I get the following errors:

> Notice: Undefined index: und in advanced\_forum\_type\_is\_in\_forum() (line 1038 of sites/all/modules/advanced\_forum/advanced\_forum.module). Warning: Invalid argument supplied for foreach() in advanced\_forum\_type\_is\_in\_forum() (line 1038 of sites/all/modules/advanced\_forum/advanced\_forum.module).

(Yes, I'm also using Advanced Forums, but I think this is more fundamentally a base Drupal 7 Forum module issue.)

This topic (which is marked as a duplicate of this) is as close as I could come to finding a similar error, but seems to imply that I'm trying to save a **forum node** (as opposed to 'foo' or 'bar') without linking it to a forum term (forum or container). Which makes some sense as when I *do* provide a valid value to the custom Term reference field, the 'foo' or 'bar node will show up as a thread in the associated forum and the breadcrumb on node 'foo' or 'bar' acts like a forum node breadcrumb. However, I really don't want my 'foo' node to act like a forum node.

So I'm guessing that trying to link to a forum from an arbitrary node using a Term reference custom field is a Bad Idea. How can I do this without hardcoding a URL?

# Answer
Use entityreference. Create a rule that generates the forum on node creation and then an action that creates an entity reference in the original node.
> 0 votes

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


# Question
Title: How do I implement a VIDEO gallery like gallery formatter but with videos?
I need to implement a gallery of videos in DRUPAL 7 like gallery formatter in Drupal 7 but with videos.

The videos are from YOUTUBE. I created a content type named "video" and I have used the module: http://drupal.org/project/video\_embed\_field for upload the code of video. Have you any idea for create the video galleries?

Thanks for your help.

# Answer
> 5 votes
If you're able to switch to a module other than video\_embed\_field I'd highly recommend the Media module along with the Media Gallery module.

You'll also want Media Youtube, I've used those three together quite a bit and they're very good.

I'd also recommend installing Colorbox to take advantage of the built-in lightbox features.

# Answer
> 4 votes
Also, check out the MediaFront module. It is a front end media solution for Drupal. It employs an innovative and intuitive administration interface that allows the website administrator to completely customize the front end media experience for their users without writing any code. In addition to this amazing module is the built-in Open Standard Media (OSM) Player.

You can embed your youtube videos, customize the look of the player, create playlist or galleries using views and much more.

# Answer
> 4 votes
The video\_embed\_field module is great. Now you just need to create a view to display a table or grid of thumbnail images and then link them to the node display page to display the embedded youtube video.

Checkout the video page on my site. It combines youtube videos with uploaded videos from the video module. When I did it a few months ago you couldn't link the thumbnail to the node display. If that's still not fixed just use a simple rewrite to "node/\[nid\]".

# Answer
> 3 votes
Personally I wasnt finding the media module pleasant to work with so based on several other modules I created a feature called youtube\_importer\_feature. Together with video\_filter and video\_filter\_field (plus the patches I added here and here that they havent committed yet) you can import directly from youtube json api and then display those videos in any way you like but most importantly using views.

---
Tags: 7, files, media
---


# Question
Title: D7 performance issues once uploaded to remote server
I just recently uploaded my D7 site to a remote server and now seem to have long wait times to do anything. I have caching turned off and am still in development mode. Could it be certain modules I am using. I tried turning devel but still same wait times. What do I need to do to speed things up? everything was quick when I had the site local...

NOTE: \- I am using Godaddy. i would think they have sufficient resources.

# Answer
> 1 votes
GoDaddy is your problem. Their shared hosting does not perform well for anything that makes moderate to heavy use of MySQL. A Drupal site which is under development and doesn't employ caching often makes considerable use of MySQL queries to generate each page.

If you're still in development, I recommend working locally instead. You can install Acquia Dev Desktop to get a Drupal compatible server environment running on your machine.

Then when you're ready to go live, upload the files and publish a copy of the database to GoDaddy. Make sure all caching is enabled, and the theme registry isn't being rebuilt on every call.

Depending on the complexity of your site, however, you may still experience poor performance. Like I said, GoDaddy's shared hosting is generally not recommended for Drupal due to their poor MySQL performance. If you can, I would urge you to seek a better quality hosting provider.

# Answer
> 1 votes
1. Check if you're experiencing the same issue for anonymous visitors?
2. Try increasing php memory
3. When was the last time you ran the cron?

# Answer
> 1 votes
You also might wanna check the results of Google Page Speed or YSlow and follow the recommendations given there. Both are available as add-ons to firebug.

---
Tags: 7, performance
---


# Question
Title: View not displaying correctly for all visitors
I have created a simple view that displays upcoming events on a page. Both the events and the pages are meant to be viewed by all site visitors. The problem that I am having is that in order to see all the events, you need to be logged into the site. I checked the nodes and permissions and don't see anything out of the ordinary. The View is supposed to display 17 events, but for the anonymous user they are only getting 12 events. Inside the view the access is Unrestricted. I have tried re-entering the 5 events that are missing and they still do not show in the View.

I also have a calendar that displays the events. Similar to the view, it is not displaying all events. The ones that are missing from the View are also missing from the calendar.

Any suggestion on what is causing this and how to fix it? Thank you.

I am using Drupal 6.2 and Views 6.x-2.16

Chris

# Answer
> -1 votes
Okay, this may or may not work...but...lately D7 has a similar issue.

If you select the view, and click the link "settings" under "Query Settings", you can make the view appear by selecting "Disable SQL Rewriting". There is a security risk, and this issue needs to be solved, ex-post-haste, but it works.

This has been an issue with every View I have seen of late, provided all your permissions are legit.

---
Tags: views, 6, users, datetime
---