title: Views 3.0 virtual numeric field handler

text:
# Question
Title: Views 3.0 virtual numeric field handler
I've created a custom handler for a counter virtual field for my module but it seems that I am doing something wrong since I can't sort it nor filter on it as a numeric field. Any one can tell what I need to add to the query method in order to actually place the values in the tables for views to use it?

```
class mymodule_handler_field_count_for_interval extends views_handler_field_numeric {

    function query() {
        $this->ensure_my_table();
        $this->add_additional_fields();
    }

    function pre_render(&$values){
        foreach ($values as $key=>$value){
            $values[$key]->count=$this->my_module_count($value->nid);
        }
    }

    function render($values) {
        $count = $values->count;
        return $count;
    }

    function mymodule_count($nid){
        $count=0;
        if (isset($this->view->filter['timestamp'])) {
            $filter_operator=strtoupper($this->view->filter['timestamp']->operator);
            $filter=$this->view->filter['timestamp'];
            $query=db_select('my_module_table','s');

                switch ($filter_operator){
                    case '<':
                    case '<=':
                    case '>':
                    case '>=':
                        //building the query
                        $query->condition('timestamp',strtotime($filter->value['value']),$filter_operator)
                        ->condition('nid',$nid,'=')
                        ->fields('s',array('sid'))
                        ->addExpression('COUNT(sid)','sid_count');
                        $result=$query->execute();
                        foreach ($result as $count_row){
                            //counting
                            $count+=$count_row->sid_count;
                        }
                        break;
                    case 'between':
                    case 'not between':
                        //building the query

                        $query->condition('timestamp',array(strtotime($filter->value['min']),strtotime($filter->value['max'])),$filter_operator)
                        ->condition('nid',$nid,'=')
                        ->fields('s',array('sid'))
                        ->addExpression('COUNT(sid)','sid_count');
                        $result=$query->execute();
                        foreach ($result as $count_row){
                            //counting
                            $count+=$count_row->sid_count;
                        }
                        break;
                }
        }
        return $count;
    }
}

```

To clarify a bit the question here is my custom module table in the install file(hook\_schema).

```
function my_module_schema(){
$schema['my_module_table']=array(
        'description'=>t('the base table for our statistics'),
        'fields'=>array(
            'sid'=>array(
                'description'=>t('The index field'),
                'type'=>'serial',
                'unsigned'=>TRUE,
                'not null'=>TRUE,
            ),
            'uid'=>array(
                'description'=>t('The user UID'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>TRUE,
            ),
            'nid'=>array(
                'description'=>t('The node NID'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>TRUE
            ),
            'tid'=>array(
                'description'=>t('The node TID for the category taxonomy.'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>FALSE
            ),
            'access_type'=>array(
                'description'=>t('The access type: 0=>web, 1 =>mobile, 2=>barcodescan'),
                'type'=>'int',
                'size'=>'tiny',
                'unsigned'=>TRUE,
                'not null'=>TRUE,
            ),
            'timestamp'=>array(
                'description'=>t('The time of viewing'),
                'type'=>'int',
                'unsigned'=>TRUE,
                'not null'=>TRUE
            ),
        ),
        'unique keys' => array(
            'sid' => array('sid'),
        ),
    );
    return $schema;
}

```

As you can see it would be very difficult to keep another table with counters because the data is modified per second/minute and users accessing the nodes are different. so what I'd like to understand is how to make views see that I am building a **numeric** virtual field and where to put it in the views tables so it does the query from its internal tables. Is that possible?

# Answer
> 0 votes
Fields, filtering and sorting are implemented by separate handlers. In your case, since your data is virtual, you will need to write your own handlers. You should probably look at extending views\_handler\_filter\_numeric and views\_handler\_sort. Then in your mymodule.views.inc file you would have something like:

```
$data['mytable']['count_for_interval'] = array(
 'title' => t('Count for interval'),
 'help' => t('Number of counts in interval.'),
 'field' => array(
   'handler' => 'mymodule_handler_field_count_for_interval',
   'click sortable' => TRUE,
 ),
 'filter' => array(
   'handler' => 'mymodule_handler_filter_count_for_interval',
 ),
 'sort' => array(
   'handler' => 'mymodule_handler_sort_count_for_interval',
 ),
 'argument' => array(
   'handler' => 'views_handler_argument_numeric',
 ),

```

);

# Answer
> 0 votes
If you want to be able to sort by values which aren't in the database you definitive need to write the data into the database.

Once you have this you can write a views integration for this field in the database and you are fine.

---
Tags: 7, views
---


title: Create an image repository

text:
# Question
Title: Create an image repository
I'm trying to create an image repository with Drupal, but I face some problems.
I want to create a node with several images attached, but since the relation between images to nodes can be many-to-many (an image can be attached to more than one node) I don't want to duplicate the same image on the server.
I've tried different solutions but none of them can really fit my needing.

* Imagefield solution:

I can easily attach multiple images to a node, but it's hard to reuse the same image.
The best solution would be using filefield\_sources, but it's a bit buggy (I can't find a way to use the IMCE integration in a proper way).

* Image solution:

It has an image browser, but without search or folder tree, it can't be used with many images.

Did anybody face the same problem and found a good solution? Thanks in advance.

**==UPDATE==**

Example:

**Product-1** \- I can attach *Image-A, Image-B, Image-C* and *Image-D* (with image module or imagefield)
**Product-2** \- I can attach *Image-E, Image-F, Image-G* and *Image-H*

**Product-3** \- I want to attach *Image-A* and *Image-F*.
I need to upload them again or I can use Image Browse (part of the Image module) to display an image picker with ALL the images uploaded before (without any search filed or filter).
I see 8 images, I can pick *Image-A* and *Image-F* and attach them to the node.

What about **Product-1200**? At that time I could have 4000 images displayed in Image Browse: it would be really hard to find the one I need to attach to the node! I would like to find a better way to select the images!

**==SOLUTION==**

I created two content types: product and image.
Image has an imagefield field.
Product has a nodereference field. I mass imported all my images with imagefield\_import.
I use nodereference\_browser with a custom view with all the filters I need to search between Image nodes and select which one to reference.

# Answer
> 2 votes
I created two content types: product and image. Image has an imagefield field. Product has a nodereference field. I mass imported all my images with imagefield\_import. I use nodereference\_browser with a custom view with all the filters I need to search between Image nodes and select which one to reference.

# Answer
> 3 votes
I haven't tried something like this before, but one way to solve it would be to.

* Create a node type to hold the images.
* Create a node reference to the image node type.

This would allow you to have several nodes reference the same image node type. You would also be able to tag images and use views on them, if you wanted to display the images stand alone, in a gallery etc.

You would need to do some work, to theme the images the are referenced though the image node, but it shouldn't be a big deal.

# Answer
> 0 votes
On my opinion, the best way is to create a content type for images, attaching a taxonmy mechanism to it and to use both taxonomy and views to show appropriate images to the user.

Hope it helps !

David

---
Tags: 7
---


title: How can I use Mootools with Drupal 6?

text:
# Question
Title: How can I use Mootools with Drupal 6?
I am looking for a way to use Mootools with Drupal 6, without disabling jQuery, of course.

# Answer
> 1 votes
You will need to load JQuery in "noConflict mode" or MooTools in "Dollar Safe mode"; your best bet is to use "Dollar Safe mode" to avoid effecting Drupal.

See MooTools, Framework Compatibility, and Dollar $afe Mode, and The Dollar Safe Mode.

---
Tags: 6, javascript
---


# Question
Title: How to pass arguments from views to node.tpl.php
Is there a way to pass arguments from views to a node template other than via selecting build modes? I use node as row style.

I used display suite + node displays to set up a custom build mode. In my node-"content type".tpl.php I then can decide via

```
$node->build_mode

```

what to render.

But first I feels like way over the top to install display suite + node displays just to pass one argument and second I ran into problems with this configuration. Everything looks fine in view's preview but after saving the view I got a "merory size exhausted" error.

So when there's time I try to reproduce this with a clean install an file a bug but at the moment I would be happy to know if there's another way to pass parameters from views to my node templates.

# Answer
> 1 votes
I finally got it. There's the Build modes module that does exactly what I want and only that.

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


# Question
Title: How to output node fields of referenced nodes as plain-text key/value pairs?
I've got a super content-type that contains at least 4 node references.

The first three references aren't always the same node-type but they contain just one referece.

The third reference can contain multiple references which are all of the same type but the type of these references my differ from time to time.

The forth reference references only one node each, which hast always the same type.

So I have a super node which references a few other nodes where number and node-type are not always the same. That's my starting point.

Now I have to send the whole content e.g. the custom fields I've created in the content-types of the sub-nodes via e-mail every time new content is created. The email should be plain text and should contain key/value pairs of the custom fields. The format is "key: value". This is fix my customer requires it and I can't change this at the moment.

To do this I want to use rules + views + rules\_views (Rules Views Integration) and this is the point where I'm unsure what is the best way to continue. I pass the node-id from rules to views to render the just created node. If I tell views to use "row style: node" and choose "full node" as "display", I got my super node with all the sub nodes inside fieldsets.

Basically thats very close to what I want and it looks like I just have to theme my node to get rid of all the HTML an plain text but how?

Do I have to use my standard node-'node-type'-tpl.php files or can I add tpl.php-files just for this specific view? Or is it possible to add a different display besides 'teaser', 'full node' and 'rss' that views will recognize and that I can theme to my liking? And if one of these is the way to go, how can I pass arguments from views to my tpl.php-file to decide how to lay out my node (for display on the site or for the email via rules)?

I hope this all makes enough sense and you can help me out.

Thx in advance.

mantuko

# Answer
Finally I got that one too :)

One can add build modes with the Build modes module an decide on $node-\>build\_mode what to render.

In the node-"super node".tpl.php one gets the node-ids of the referenced nodes from $node. Then one can node\_load() these nodes into a variable and theme them.
> 0 votes

---
Tags: views, 6, theming, nodes, rules
---


# Question
Title: How can I render a view on user-profile.tpl.php that includes the user name as an argument in Drupal 7?
In Drupal 7, on a custom user profile page (using user-profile.tpl.php) I would like to place a view that references all nodes of a specific content type that has that user as a reference. (The user may, or may not be an author of the node.)

# Answer
> 1 votes
use views\_embed\_view to embed a view:

```
$views = views_embed_view('VIEW_NAME', 'DISPLAY_ID');
print render($views);

```

The DISPLAY\_ID is typically 'page' or 'block' depending on the displays you have setup in views.

You can build the view with a contextual filter to get all nodes with a user reference.

If you don't need to embed the view in the middle of your user profile you can just use a block output and show that block before or after your user profile.

---
Tags: views, users
---


# Question
Title: How do I override a function in a module
I want to batch override (there are hundreds of terms) menu paths generated by the Taxonomy Menu module for a custom menu I require. I know not to edit the module itself. I assume I create a separate module containing the replacement function to substitute the desired path I want, but I am not certain how to direct Drupal to use it instead of the original. Or am I using the wrong strategy for this?

UPDATE: I have solved the specific example in the question using a panel tied to a view. However, I am still interested in the question itself. A theme function can be overridden by including the replacement function with my theme name replacing the original theme name in the function name. Drupal handles the substitution from there; the same renaming option is not available for module functions.

I have continued to research this and found several posts at Drupal.org, that suggests it is not possible to override module functions in the same way you override theme functions. There was a module for this in Drupal 6 (Override\_Function), but it required additional software and appeared to have some problems working with PHP 5.2 & 5.3. The only workaround I have found so far is to hack it, but keep track of your changes so that it can be reinserted after updates.

# Answer
> 4 votes
It sounds more like you want to use hook\_menu\_alter to override what the Taxonomy Menu module's hook\_menu function does.

---
Tags: 7
---


# Question
Title: enabling users to upload pictures from their harddrive in wysiwyg
I have wysiwyg module with IMCE enabled so I can browse the server of my site is located for pictures I can upload to add to my content. But the idea now is to have users that are bloggers to be able to upload pictures from their harddrive on to the site using a wysiwyg editor (in this case CKEditor).

Anyone experience with that and know how to do that or know of a good tutorial for this. When searching for an answer online I found info that explained how to add CCK fields to my content type but this is not what I want. I want bloggers to be able to choose where they put the pictures in text and how many.

# Answer
> 1 votes
I have used the WYSIWYG image upload module successfully on my previous D6 sites. It has good documentation and a simple interface to do what you need.

---
Tags: 6, wysiwyg, files
---


title: views filter problem

text:
# Question
Title: views filter problem
Filters on Views only give the possibility for static values. I want to show only nodes with a node ID that is an odd number.

Using PHP code, this is what the filter should do:

```
if ((nid % 2) == 1) {
  return TRUE;
}

```

Can anyone tell me how to do this?

# Answer
> 2 votes
The Views PHP module would work for this.

---
Tags: views
---


# Question
Title: Drupal UberCart how can users see thier own orders
I'm setting up a shop on one of my sites, and I've set it so users create an account when they order. When users log in, I cannot workout the link to show their past orders, or registered addresses.

Is there anything built into UberCart for this? All I've found are some permissions and I've set "View own order." Do I have to write up a module for this?

# Answer
If the users are not anonymous users, they should have a tab in their user profile that shows their orders.
> 1 votes

---
Tags: ubercart
---


title: first module, hook_menu/FAPI problem

text:
# Question
Title: first module, hook_menu/FAPI problem
I'm fairly new to Drupal and made my first module. It works. Yay!

*What I have*: Calling `/form-test/186` (nid) Nid gets loaded, renders content.

*What I want*: The same but with an simple submit button at the end, that calls a

```
function exportIt() {
  // put $output from formtest_page() in email
}

```

when clicked, not before.

```
    <?php

/**
 * Implements hook_menu().
 */
function formtest_menu() {
  $items['form-test/%'] = array(
  'title' => 'Export von:',
  'page callback' => 'formtest_page',
  //'page callback' => 'drupal_get_form',
  'page arguments' => array(1),
  //'page arguments' => array(formtest_simple_form),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK, );
  return $items;
}

function formtest_page($nid = NULL) {

  $node = node_load($nid);
  if ($node) {
    $title = $node -> title;
    dpm($node); //Why is this not get displayed?
    drupal_set_title('Klicket Export von: ' . $title);
    $output = '';
    $items = array("<b>titel: </b>" . $title,
    "Where is my beef?" );

    $output .= theme('item_list', array('items' => $items));
    //drupal_get_form('formtest_simple_form');
    return $output;

  }
  return;
}

function exportIt() {
  // put $output from formtest_page() in email
}

//simple submit form
function formtest_simple_form($form, &$form_submit) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Export an Klicket'));
return $form;
}

```

I'm having basic conceptional issues I guess. I either can render the submit Button or the Output, but not both.

# Answer
> 1 votes
The correct code is similar to the following one.

I will add some notes about the code as I wrote it:

* If you use "form-test/%node" (instead "form-test/%"), the node will be loaded from Drupal, and if there are some problems with loading it, it will report an error (404, page not found) to the user; in this way, you don't need to call `node_load()` as that is already done by Drupal.
* There is a callback that returns the title Drupal should use.
* I am not sure I translated correctly the strings you were using (I guess it was Swedish, but I am not positive, as I don't know Swedish); I had to translate the strings, as `t()`'s argument is a string in English, which will be translated in the language set for the site.

```
function formtest_menu() {
  $items['form-test/%node'] = array(
    'title' => 'Export',
    'title callback' => 'formtest_title',
    'title arguments' => array(1),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(formtest_simple_form, 1),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function formtest_title($node) {
  return t('Export Klicket from @title', array('@title' => $node->title));
}

function formtest_simple_form($form, &$form_state, $node) {
  $form['#node'] = $node;

  $items = array(
    t("<strong>Title: @title</strong>", array('@title' => $node->title)),
    t("Where is my beef?")
  );

  $form['item_list'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
  );

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

  return $form;
}

function formtest_simple_form_submit($form, &$form_state) {
   // Write the email.
   // If you need the node object, it is in $form['#node'].
}

```

# Answer
> 0 votes
I do not get what your problem is but usually what you do is, set `page callback` to `drupal_get_form` , `page arguments => array('my_form_id');` then instead of naming it exportIt you name it `my_form_id_submit`.

---
Tags: 7, routes
---


# Question
Title: menu_get_active_trail returns page not found
I want to add a meta description to a custom module 'mymodule', but this doesn't load as expected.
The problem is in the active trail, when menu\_get\_active\_trail is called inside array 1 the router\_path = node/% and the title is page not found.
How can the active trail be fixed?
This works on other sites.

```
function mymodule_html_head_alter(&$head_elements) {
// menu_get_object with load function at position 2

if ($myentity = menu_get_object('myentity', 2)) {
  dpm(menu_get_active_trail());

  $head_elements['meta_description'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => $myentity->name,
      ),
    );
  }
}

```

# Answer
> 0 votes
First, you have to make sure that the active menu is actually set. In Drupal 6, we did this like this: http://echodittolabs.org/blog/2010/04/drupal-fails-set-active-menu-trail-causing-context-fail.

Next, clear the cache, and then refresh the page. Yes, `dpm()` has a lag or something. If you see the right data, great.

My data was actually being cached as page not found, when actually it had set the correct data. Don't know why.

So, your debug info may show "Page not found" when, what is being rendered would be correct. The way you see if this is the case is by clearing the cache and refreshing.

This is for Drupal 6, but the principles likely hold for Drupal 7. Unfortunately, I doubt anybody rewrote the crufty old menu system. Too much AJAX and glitz.

---
Tags: 7
---


# Question
Title: Retrieving customer information to use in drupal commerce payment module
I'm new to drupal development and am programming a payment module for the new drupal commerce module. It's will be a basic api module that allows the user to stay on the site and makes a separate curl call to send the data and use the response to indicate success or failure.

I copied the authorize.net aim payment module and have so far gotten to a point where I'm correctly posting the information that's being sent using the authorize module. However the payment system I'm using requires the customer name and billing address and I'm not sure about how to go about gathering that information. I know in the order there is a user/customer profile id but I don't know how to get any other information about the customer. I do know that the billing address is gathered, it just isn't sent to authorize.

# Answer
The customer profile is attached to the order, and it has an address field that holds the information. To get it you could do;

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$address = $order_wrapper->commerce_customer_billing->commerce_customer_address->value();
$postal_code = $order_wrapper->commerce_customer_billing->commerce_customer_address->postal_code->value();
...

```

It's a lot simpler to use the entity metadata wrapper as shown above. What it does is that it loads the customer profile entity for you and let you access it's field.
> 8 votes

# Answer
@googletorp is right about your EntityMetadataWrapperException problem. For me I had entitycache installed. By disabling it and clearing the cache I was able to fix the same problem. The drush commands for clear cache, or the drupal clear cache does not clear the entitycache.
> 2 votes

# Answer
I get the exact same, depending on ordering of the panes-- the entity has not been saved when you call the above.

You should look at the pane values to find what you need. If you still need help, post again and I'll find the Drupal thread on this issue / reply what exactly you are doing.
> 0 votes

---
Tags: commerce
---


# Question
Title: Only create taxonomy terms on node approval?
Right now nodes on my site are unpublished by default because I want to manually approve user submitted content. How can I make it so that user submitted taxonomy terms are not created until I manually approve the corresponding node?

# Answer
> 1 votes
If you are OK with the taxonomy terms existing for a brief second then you can move them to a vocabulary otherwise unused on hook\_nodeapi insert and, upon hook\_nodeapi update if status flips from 0 to 1 then move them back to the vocabulary attached to the node.

```
  function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    switch ($op) {
      case 'insert':
        $tids = array_keys($node->taxonomy);
        $placeholders = db_placeholders($tids);
        db_query("UPDATE {term_data} SET vid = 654321 WHERE tid IN ($placeholders)", $tids);
        break;
      case 'update':
        if ($node->status) {
          db_query("UPDATE {term_data} SET vid = 23 WHERE tid IN (SELECT tid FROM {term_node} WHERE nid = %d)", $nid);
        }
 }

```

Where 654321 is a vocabulary you created but didnt assign node types to it and 23 is the vocabulary your nodes can use. This way the terms get created but other nodes cant use 'em, an appropriate View wouldn't see them etc. It's a hack. But a very effective hack.

# Answer
> 1 votes
As far as I can see, this would require a custom module. You would have to do something like this (tailor to your needs; I don't know if you're using publishing status to represent approval status).

```
    <?php
      function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
        switch ($op) {
          case 'presave':
            if (!empty($node->taxonomy) && $node->status == 0) {
              // Write some logic to save the data to your module's DB table, e.g.
              // _mymodule_get_taxonomy_temp() would contain a database query or
              // something to get the record.
              $record = _mymodule_get_taxonomy_temp($node->nid);
              $record_exists = !empty($record);
              $taxonomy_temp = ($record ? $record : new stdClass());
              $taxonomy_temp->taxonomy = $node->taxonomy;
              $taxonomy_temp->nid = $node->nid;
              if ($record_exists === FALSE) {
                drupal_write_record('mymodule_taxonomy_temp', $taxonomy_temp),
              }
              else {
                drupal_write_record('mymodule_taxonomy_temp', $taxonomy_temp, 'nid'),
              }
              unset($node->taxonomy);
            }
            elseif (!empty($node->taxonomy_temp && $node->status == 1)) {
              // Retrieve the saved taxonomy and put it back into the node.
              $record = _mymodule_get_taxonomy_temp($node->nid);
              // We append it to any changes made during the approval process.
              $node->taxonomy = array_merge($node->taxonomy, $record->taxonomy);
              // Clean up the database record
              _mymodule_delete_taxonomy_temp($node->nid);
            }
            break;
        }
      }
    ?>

```

Note that this is strictly sample code. You might want to retrieve the terms using hook\_form\_alter instead and show them in the tags box as if they had been added. In any case, the key is not to have them in `$node` when `taxonomy_nodeapi()` runs and saves them.

---
Tags: 6, workflows
---


# Question
Title: Does variable_get() first go to 'variable' table in the database or the $conf array in settings.php?
I can't tell from the source for `variable_get()` for Drupal 6 whether it first looks for something in the variable table in the database, or the `$conf` array in settings.php.

Also, if I were to add something in some code to the `$conf` array, would I need to do anything in order for variable\_get to see it?

```
global $conf;
$conf['myvalue'] = 'newvalue';

```

If 'myvalue' were set to 'oldvalue' in settings.php, then what would I need to do in order for `$conf['myvalue']` to now return newvalue instead of oldvalue?

# Answer
> 4 votes
The function that is responsible for loading the values of the Drupal variables in memory is variable\_init(), which executes the following code:

```
  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

```

`$conf`, the value passed to the function from \_drupal\_bootstrap() is the array read from the settings.php file. The function that reads the configuration file is conf\_init(), which is called from `_drupal_bootstrap()` before calling `variable_init()`. As you see in the code, the values read from the database are then overwritten with the values find in the `$conf` array.

Similar code is present in Drupal 7 (see drupal\_bootstrap(), \_drupal\_bootstrap\_configuration(), and \_drupal\_bootstrap\_variables()).

The only way to use the value read from the database is to remove the value set in settings.php.

---
Tags: configuration
---


# Question
Title: How to have postings in blog with custom teaser length and read more links
I know this is a common request, but I have had no luck finding any answer. I am setting up a single user blog on my site. The blog has it's own page.

I have made a custom content type based on the Article content type. Then set up a View that displays these for the the blog page. The only thing I can't seem to make happen is to set up a custom teaser length with read more links that take you to each full Article node.

When I set the *Row style: node/Page row style options/build mode* to *Teaser*, I get the shorter teaser length, but no *read more* link to the full node.

I am using Drupal 6.

# Answer
> 1 votes
Can you use "Rewrite the output of this field" on the teaser (or the body) to limit it to a certain length? You can break on a word and show an ellipsis, and you will also be able to show the Read More link as usual. You have to use a row style that will let you use Fields for this, though. Otherwise, you could try to find the function that Views uses to do the same thing and add a template file and preprocess function to alter the teaser length in the same way.

Check the "Information" setting on the bottom-left of the Views 2 UI to see the available templates. You basically copy the base version of one of these to your theme directory, name it as specifically as is needed, and then change it to match your needs. In this case, you wouldn't change it, but you would implement THEMENAME\_preprocess\_PATTERN (\<--- depends on which one) to style the field value appropriately.

# Answer
> 0 votes
You can add your own "Read More" link by adding a Content: Link field, and adding your own text, e.g, "Read More".

---
Tags: 6, nodes
---


# Question
Title: Regions. how can I disable a region? (not disabling blocks)
I want to disable a region, to not show blocks in this region to an specific page. I want this because, I have several blocks (more than 20) so in this case is necessary enter to each block, and configure in what page or pages must not be showed. Well I can do that, I just want to know if exist some way to make this task in a more practical way, or in a programmatically way.

I am using Drupal 6.

# Answer
The quickest way is to unset the region you want hidden in your theme's template.php. For example:

```
function YOUR_THEME_preprocess_page(&$vars) {
  if (drupal_is_front_page())
    unset($vars['left']);
}

```
> 1 votes

# Answer
The context module is a very handy way to control blocks on a site which uses them extensively. It allows you to define contexts which show and hide blocks. It will stop the blocks from even being loaded so will help performance.

It makes it much easier to define where and when the blocks appear. Rather than defining things per block you define what blocks appear per context.

This video seems to explain things well.
> 4 votes

# Answer
You may want to try the Region Visibility module.

They say:

> This module allows privileged users to set role or page specific visibility settings for regions, similar to the block visibility settings in Drupal core.

I didn't try it out myself, but it seems useful.
> 2 votes

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


# Question
Title: Set a block region from the block edit page
I used Drupal since 4, and it always bothered me that the the block edit page doesn't include block region settings. One must return to the Blocks list to change that. It would be so much nicer if the block edit page included the region options, when using the contextual Configure links on the page.

There is no module dedicated to this on Drupal.org, so maybe there is a good reason for not doing this, like a technical limitation. Or maybe this is not useful to anyone else but me.

Is there a module for setting the block region from the block edit page? I'll create one if there isn't.

Thanks.

# Answer
> 1 votes
In Drupal 7 you have the option to set the region of the block within the block's edit page.

I haven't seen a module for this for Drupal 6 let alone earlier versions. I would strongly recommend upgrading to Drupal 7 for this feature and the plethora of other desirable features of Drupal 7 compared to it's predecessors.

I hope that helps...

---
Tags: 7, theming
---


# Question
Title: What are the best e-commerce modules/setups?
Googling for "Drupal E-commerce" brings up a ton of old results, and I wanted to weed out all the garbage. I'm a regular on SO but I thought that I might get better insight/advice here.

Running Drupal 7.9 (multiple sites will be installed but running their own Drupal install), what e-commerce packages should I install (shopping cart and payment options)?
What are the pitfalls to look out for?
What theme do you suggest, that is geared towards E-commerce?

# Answer
> 3 votes
I have not yet built an e-commerce site on D7, so I cannot get really specific.

That said, the obvious starting point for e-commerce on Drupal 7 is the Drupal Commerce package. Just start with the basic package, see if it fits your needs, and install add-ons if you need them. There even is a dedicated Drupal Commerce website with documentation, a forum and more.

There are a couple of themes that are specifically geared towards e-commerce, for instance Acquia Prosper and AT Commerce.

# Answer
> 3 votes
The Ubercart module for Drupal 6 was always a winner for me.

That said the Commerce module does look very promising but I have yet to try it out fully.

The Ubertcart module for Drupal 7 is coming along wonderfully too, so either this or the Commerce module would be suitable, but I would hint towards starting with the Commerce module as it's a dedicated Drupal 7 e-commerce solution and has some good themes to start with too as pointed out by marcvangend.

# Answer
> 1 votes
You could also try checking out Martplug. It's a complete distribution that contains Drupal Commerce and a load of other gubbins to get you off the ground! I've only played around with it, not used it in production yet..but still looks pretty neat!

With regards to themes, Omega is a great starting point (and also encompases responsive design)..and if you combine it with the Context and Delta modules then it's a surefire win!

---
Tags: 7, theming, commerce
---


# Question
Title: How to retrive menu_get_object() in javascript, jQuery?
I'd like to use the $node object in JavaScript, preferably Drupal's DOM. Is there a recommended way to do this in Drupal?

# Answer
There are several ways to go about this. The most straightforward is use template\_preprocess\_node , drupal\_add\_js, and drupal\_json\_encode.

Something like this:

```
function mytheme_preprocess_node (&$variables)
{
  $node = $variables['node'];

  drupal_add_js(array(
    'mytheme' => array(
      'node' => $node,
    )
  ), 'setting');
}

```

The node will then be JSON encoded as `Drupal.settings.mytheme.node`. The above is untested, but will be a decent starting point. Keep in mind that if you have multiple nodes on a page, then this will get called multiple times. You would need to add some logic to handle these cases.

If you do this as part of themeing, rather than a module via the Node API, then all modules that alter the `$node` will have run at that point, so all data should be there. Personally, I would only add the data that I need. `$node` can get pretty big, so adding all of it would be a lot of JS on a page.
> 1 votes

---
Tags: 7, nodes, javascript
---


# Question
Title: Does Page Manager redirect work on alias paths?
I am attempting to do a simple custom page redirect using page manager following the example from `NodeOne.se` videos on Page Manager. While the video works, my attempt does not and I can't see the difference other that the alias path I use.

The URL I want to intercept is `specs/%spec` so I have created a custom page with that URL. I have configured the page with one argument to interpret `%spec` as a taxonomy term ID.

Next I created a variant set to perform an HTML redirect (301) to the URL `materials/%spec:name/facts` (This URL will call a view). There are no selection rules so all content will pass. Thee are no contexts or relationships since the argument for the term name is already visible in the summary of contexts present.

My expectation is that a URL such as `Example.com/specs/term1` should redirect the website display to the contents called by the view page `/materials/%/facts` using with `term1` applied as a contextual filter giving me a URL of example.com/materials/term1/facts. Since the URL is passing the context to the view, I should not need to pass arguments through page manager/panels UI.

My result is when I enter the `specs/term1` URL, the taxonomy page for that term is shown and the URL is not changed.

The only thing I can guess is that this does not work on aliases. Any ideas on why this fails anyone?

# Answer
Yes panels will read the path alias. I have discovered two related reasons why this problem might be occurring.

1. Many of my taxonomy terms are two words long. Panels does not have a provision (views does) to convert the spaces to dashes. The panel redirection variant is not reacting to the URL because it is looking for an argument that does not have dashes generated by `%spec:name`.
2. I tried the same redirect using the panel provided by the system `/taxonomy/term/%term` and it succeeded in placing the redirect path in the URL, although the redirect did not work. This is because the term name had two words and was inserted with a space in it.

There are several LEARNING Points for me in this answer:

First, I discovered that the actual Drupal path to nodes and terms are fully interchangeable. I thought that if a URL was using an alias, I was restricted to working with the alias format. The ability of panels to intercept the Drupal name pattern `taxonomy/term/%term` out of the alias drove home to me the fact that Drupal sees them as exactly the same.

Second, When this problem arose, I thought too big, too fast. I suspected a bug in the module or a major misunderstanding of how the selections in the form connect to each other to generate the action of the panel variant. I have had similar problems using views, which also very a complex module. The problem turned out to be a minor, easily overlooked error.
> 2 votes

---
Tags: 7, views, taxonomy-terms, panels, chaos-tool-suite
---


# Question
Title: What license can I apply for a theme I sell?
I'm interested in creating a premium theme to sell online; I've heard a lot about the Drupal GPL licensing and wanted to make sure I've got my facts right.

If I understand it correctly, everything that works with Drupal, such as the template files and any Drupal related JavaScript counts as "derivative works", so those bits I will have to distribute as GPL.

However, things like the CSS and Images that make up most of the "design" of my theme I can distribute under my own licence, and therefore charge for.

I used the Collective Mind's End User License Agreement (EULA) as a guide.

Is this correct? Does this change if I use one of the many base themes in Drupal? Are there any practical consideration?

# Answer
One technique you might consider is committing your basic theme to a project on drupal.org, distributed under the GPL. Then, develop premium css and graphics that can be installed over your basic theme using instructions that you provide. The later package could be distributed under a license of your choice.

It is okay to use a separate license for the css and graphics files because they can be considered separate works that stand on their own. To make it more clear that the css and graphics are separate works, you could distribute them with a static html file that shows what the final theme should look like. Your customer has the right under the GPL to combine the css and graphics with his GPL theme; tt would be a violation of the GPL to distribute the combined works, but they can be used by the licensee of the separate works (your theme).

Finally, regarding the "basic theme", note that there is nothing special about css and graphics vis-a-vis the GPL; it is still necessary to deliver the "source" of your works along with the "binaries" when they are included in a GPL-licensed distribution. If you built the css using some tool, then you must deliver the source files that were used to produce that css. If you created the graphics in photoshop with layered psd files, then you must also distribute those files with your theme, and so on.

**Edit Edit Edit:** Reworked my prior answer(s) for clarity, and to remove a mistake.

**Postscript:** I believe that the FAQ referenced below is partially incorrect; graphics and css are not excluded from the GPL because they are "data"; if they are an integral part of the work being distributed, then they are covered by the GPL as much as the code is.
> 2 votes

# Answer
If you are developing a theme(free or premium), you must do so under the terms of the GPL, as it is a derivative work of Drupal. In case you haven't read this:

http://drupal.org/licensing/faq#q7
> 1 votes

---
Tags: theming
---


# Question
Title: Problem with home page misaligned on website
The site in question is http://johannabolhoven.co.uk/.

As you can no doubt see, the home page seems to be misaligned from the other pages.
I've got the disable breadcrumbs module installed and I'm wondering if the problem is that the space is still being left for the disabled breadcrumbs, but it could also be something else.

I've tried (to the best of my ability) to disable the breadcrumb div in the template files, but that didn't seem to help either.

# Answer
Found it. You have a custom content pane when you have an image that is inside of a p tag. That p tag has a margin of 12px on the top and bottom and the image has 10px border on all sides. Remove that and you should be good to go.

```
<div class="art-sheet-body">
 <div class="art-content-layout">
  <div class="art-content-layout-row">
   <div class="art-layout-cell art-content">
    <div class="art-post">
     <div class="art-post-body">
      <div class="art-post-inner art-article">
       <div class="art-postcontent">
        <div class="region region-content">
         <div id="block-system-main" class="block block-system">
          <div class="panel-2col-stacked clearfix panel-display">
           <div class="center-wrapper">
            <div class="panel-col-first panel-panel">
             <div class="inside">
              <div class="panel-pane pane-custom pane-1">
               <div class="pane-content">
                <p>
                 <img style="width: 200px; height: 78px;" src="/sites/default/files/Signature orange.png" alt="">
                </p>

```

I got this from http://johannabolhoven.co.uk/personal\_shopping.

Let me know if there were other issues that you had, but the home page being higher than the other pages was the only thing I could find.
> 1 votes

---
Tags: 7, panels, breadcrumbs
---


title: What is  $form_state used for?

text:
# Question
Title: What is  $form_state used for?
What is `$form_state` typically used for in the context of the Form API if it is used as an argument?

Specifically, I'm looking for an example of when it is used.

# Answer
> 53 votes
`$form_state` is one of the arguments passed to a form submission handler, or a form validation handler; its main usage is to store the form submitted values (in `$form_state['values']`), but it also contains values for other purposes.
The documentation for `drupal_build_form()` shows a list of the values contained in that array, which includes:

> * rebuild: Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and `drupal_redirect_form()` will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect. This is used for multi-step forms, such as wizards and confirmation forms. Normally, `$form_state['rebuild']` is set by a submit handler, since it is usually logic within a submit handler that determines whether a form is done or requires another step. However, a validation handler may already set `$form_state['rebuild']` to cause the form processing to bypass submit handlers and rebuild the form instead, even if there are no validation errors.
> * redirect: Used to redirect the form on submission. It may either be a string containing the destination URL, or an array of arguments compatible with `drupal_goto()`. See `drupal_redirect_form()` for complete information.
> * cache: If set to `TRUE` the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, `$form` and `$form_state` are built from scratch during each of these page requests. Often, it is necessary or desired to persist the `$form` and `$form_state` variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. A prominent example is an Ajax-enabled form, in which `ajax_process_form()` enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.) Note that the persistence of `$form` and `$form_state` happens automatically for (multi-step) forms having the 'rebuild' flag set, regardless of the value for 'cache'.
> * storage: `$form_state['storage']` is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within `$form_state` (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses `$form_state['node']` in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

Other functions that get `$form_state` as argument are `hook_form_alter()` and `hook_form_FORM_ID_alter()`.

An example of function that uses `$form_state` is `comment_form_submit()`, a form submission handler, which contains the following code.

```
function comment_form_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $comment = comment_form_submit_build_comment($form, $form_state);
  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }
    comment_save($comment);
    $form_state['values']['cid'] = $comment->cid;

    // Add an entry to the watchdog log.
    watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));

    // Explain the approval queue if necessary.
    if ($comment->status == COMMENT_NOT_PUBLISHED) {
      if (!user_access('administer comments')) {
        drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
      }
    }
    else {
      drupal_set_message(t('Your comment has been posted.'));
    }
    $query = array();
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    if ($page > 0) {
      $query['page'] = $page;
    }
    // Redirect to the newly posted comment.
    $redirect = array('node/' . $node->nid, array(
      'query' => $query,
      'fragment' => 'comment-' . $comment->cid,
    ));
  }
  else {
    watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
    drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
    // Redirect the user to the node they are commenting on.
    $redirect = 'node/' . $node->nid;
  }
  $form_state['redirect'] = $redirect;
  // Clear the block and page caches so that anonymous users see the comment
 // they have posted.
 cache_clear_all();
}

```

To understand what `$form_state['values']` contains, you need to look at the values added to `$form` in `comment_form()`. For example, `$form_state` contains `$form_state['values']['name']` because `$form` contains `$form['author']['name']`. Generally, if `$form['field']` is a form field, then `$form_state` will contain `$form_state['values']['field']`.

---
Tags: forms
---


# Question
Title: Optimize CSS & JS breaks IE & FireFox (All Themes)
**Problem**
Theme is not showing properly on my production server for individuals using Internet Explorer & Firefox after setting the CSS & JS Optimization options to enabled. I initially thought the theme was broken for IE, however upon further review I realize the reason IE didn't work while CSS/JS optimization was disabled is because of Internet Explorer not handling more than 31 CSS files.

> To Help with troubleshooting I used the Site Documentation module to get all the info on the site, modules, etc. Here is the link to it.

**Drupal Core:** 6.22
**Theme:** 0 Point, Zen, Tao, PixtureReloaded

* It is not a multi-site installation
* It is on the same web hosting account as 3 other drupal installations, the 3 other drupal installs do not exhibit the same issue.

I used the Backup & Migrate module to copy the MySQL DB and used FileZilla to download the site/default/files/\* folder(s) & files, site/all/modules, libraries, & themes files. I restored the DB & sites/default/files folder to a test server. Setting "Optimize CSS & JS" to enabled fixes the 31 css files problem for Internet Explorer and both FireFox and Internet Explorer are able to view the website theme as normal.

The absolute strange quandry here, is when I enable CSS/JS Optimization on the production server it breaks the theme for both IE and FireFox. Chrome and mobile devices (android & iPhone) are unaffected. I have not checked any other web browsers for issues.

I have listed the themes that I have specifically checked. Where do I continue troubleshooting this from here? I thought maybe changing the theme would fix it, however it has not.

**Troubleshooting**
Enabled the *Optimize CSS/JS Files* options by

* Making setting the *File System \>\> Public* option.
* Setting the *Performance \>\> Optimize CSS/JS* options to enabled.
* Clearing the Cache and Rebuilding the Theme Registry.

Switched the Theme to PixtureReloaded (an adaptive theme) and repeated the steps above.

Switched to Zen and repeated the steps above.

Checked the file system permissions for sites/default/files to make sure there was read/write access and there is for owner/group/other

It seems that regardless of the theme I switch it to it does not fix the IE issue, and when I optimize the css/js files it breaks the website for FireFox users as well.

-- Edit 11/1/2011 1:30AM UTC -- As per suggested I re-encoded all the files in the theme from ANSI to UTF-8 without BOM.
Backed up the original theme folder, after taking the site offline
Uploaded via ftp the re-encoded theme
Ran update.php, cleared the caches, rebuilt the theme registry
Issue persists.

-- Edit 11/1/2011 4:57 PM UTC --
I also tried using the Garland, Mannilli, and Bluemarine themes with the same results (I tested this last night when I took the site offline).

-- Edit 11/1/2011 6:53 PM UTC --
I took the site offline, changed the settings to "Optimize CSS: Enabled"
Viewed Source for Chrome, FireFox, & IE9
I am able to click on the links for the CSS files and browse them, each css file is the same, and I did a DIFF/Compare of the tag content and except for a session ID that ubercart uses for the shopping cart each head section is the same.

# Answer
Resolution:

* Backup the contents of the sites/default/files folder excluding the css, ctools, & js folder (I am assuming if you have another module or code creating css files that it should also be excluded from the back up)
* Delete the sites/default/files folder (to remove the css, ctools, & js folders), YES I had to delete the entire files folder or this does not work and the issue persists.
* Allow drupal to recreate the css, ctools, & js folders.
* restore the contents of the sites/default/files folder (***EXCLUDING*** the css, ctools, & js folder)

*Notes:*

* It does not matter if the CSS & JS optimization is set before or after the above steps the results are the same. The site theme will work again for both FireFox & Internet Explorer
* Restoring the css, ctools, & js folders/files will break the site again.

I do not know enough about drupal or php to trace this issue to it's root cause, if someone would like to offer to do this I am happy to supply the necessary files/folders to do so just contact me through here.
> 0 votes

# Answer
One possibility is that one or more CSS files have a Unicode BOM at the beginning. The CSS optimizer that Drupal uses (at least the one in 6) doesn't work properly with these. IIRC, the first rule gets mangled if it is the very first line in the file.

Switching the encoding with Notepad++ is the easiest way to fix this in you are on a PC.
> 0 votes

---
Tags: theming
---


title: Conditional Views exposed filters

text:
# Question
Title: Conditional Views exposed filters
So, I have a view that has multiple exposed filters. If someone selects one of the filter options, I need the rest of the exposed filters options to change dependent on what was selected in the first.
For example three of the filters are: instruction, video duration, learning level.

If a specific instructor is selected, the video duration and learning levels should change to shown only the videos of that instructor. (These are not based on taxonomy.)

I am using Drupal 6 and Views 6.x-2.

# Answer
Here is one module that I found that will do this work for me. Views hacks, selective views Filters: Views Selective Exposed Filters.
> 3 votes

---
Tags: 6, views
---


# Question
Title: How to access User Picture field for a comment in Views?
I have a Views table with each row showing the node title, node author, and node author picture. I am also adding the last comment title and last comment author to each table row. I would like to add the last comment user picture but that doesn't seem possible from looking at the code.

There is a database table called Node Comment Statistics which Views uses to query the last comment author name and UID.

I would like to somehow use that last comment UID to query the database for the user picture and render it through the theme\_user\_picture function adding it the View or attaching it someway to the Username with some markup.

Is this possible?

# Answer
> 6 votes
1. Add a relationship- Comments: User
2. Add a field- User: Picture (assign Relationship: User)

---
Tags: views, media
---


# Question
Title: CyberSource order gets stuck 'In Checkout', never completes
I am using CyberSource, with ubercart 2.6. I am using the CS test server. When I make a payment, everything goes through, but the order gets stuck in 'In checkout' when viewing the status at '/admin/store/orders/sort/all'.

In watchdog, I receive the following error: Receiving invalid payment notification at URL for order ##

Does anyone know what might cause this issue?

# Answer
Figured out the issue: In uc\_cybersource.module there is a line in function `uc_cybersource_hop_form($form_state, $order)` that reads

```
$data['orderPage_version'] = '4';

```

It needs to be changed to the current orderPage version (as of this writing it is 7).

```
$data['orderPage_version'] = '7';

```

This should definitely be documented somewhere!
> 2 votes

---
Tags: 6, ubercart, payment-gateways
---


# Question
Title: How to add a text Autocomplete Widget programmatically
Trying to include a text Autocomplete Widget in a compound field (more here) using the snipped below.. but the field does not autocomplete. What am I doing wrong?

```
  $element['contact_name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => $defaults['contact_name'],
    '#weight' => 2,
    '#size' => '100',
    '#max_length' => '255',
    '#widget_type' => 'autocomplete_widgets_flddata',
    '#autocomplete_match' => 'contains',
    '#autocomplete_case' => '0',
    '#widget_module' => 'autocomplete_widgets',
  );

```

# Answer
Ok, so if you're trying to do it through hook\_form\_alter, you have to read the documentation on altering CCK fields.

The short version: the CCK fields are processed after the form is built. If you want to change anything in them, you have to add a callback to `$form['#after_build']` (but **do not replace the array**, just add to it). Then implement the function, change values in `$form` and return the `$form`.
> 2 votes

---
Tags: 6, entities, ajax
---


title: Multi-site sharing content

text:
# Question
Title: Multi-site sharing content
Is it possible to share content/nodes in a drupal multisite environment.

For example:

Content type "Story"

* Site 1- Use this content
* Site 2- Don't use this content
* Site 3- Use this content

It seems the drupal multisite environment suggests using table prefixes for different sites.

# Answer
> 3 votes
I think this is what the domain access module is for.

# Answer
> 1 votes
You could also use the deploy module to push content to specified sites

---
Tags: nodes, multi-sites
---


title: One menu, many levels, few editors

text:
# Question
Title: One menu, many levels, few editors
How can I have 1 menu (site map), hierarchical structure like:

* Dept 1
    + Abc
    + Def
    + Ghi
* Dept 4
    + AAA
    + BBB
        - ffe
        - ffg
        - ffx
    + CCC

With possibility to delegate editing permission of subtrees to some users? I.e. : main admin edits the whole menu, admin A edits only submenu in Dept1, admin B edits only submenu BBB in submenu Dept 4 ...

Is there any module which can be used to do that? I know that Organic Groups has possibility of creating menus for every group with feature of editing permission to group members. But I'd rather have 1 big menu for the whole site...

# Answer
> 1 votes
You haven't specified which Drupal version you are using, but check out Menu Subtree Permissions for D6.

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


# Question
Title: How to inspect outgoing email content during a SimpleTest?
I see that SimpleTest has a few built in mail functions to check for send success etc, but how can I send a message, assert its content and then click a link within that content during a test?

What is the standard or most common way to test unsubscribe, or account verification links in emails with SimpleTest?

# Answer
> 6 votes
Simpletest automatically captures sent mails during a test and allows you to fetch them using $this-\>drupalGetMails() in the test class.

I did something like this recently in tests I wrote for the Simplenews project, to test subscription confirmation here.

---
Tags: 7, emails, testing
---


# Question
Title: How to create a user with custom profile fields for a SimpleTest
How can I programmatically create a new user for use during a SimpleTest? The user must have certain custom fields populated during the registration.

I'm using `$this->drupalPost('user/register', $edit, 'Create new account');` to create the account currently as I do not see a way to populate custom profile fields with `drupalCreateUser()`.

```
$edit = array(
      'name' => $this->randomName(17),
      'mail' => $this->randomName(17) . '@example.com',
      'field_owner_first_name[und][0][value]' => $this->randomName(17),
      'field_owner_last_name[und][0][value]' => $this->randomName(17),
      'field_owner_title[und][0][value]' => $this->randomName(8),
      'field_business_name[und][0][value]' => $this->randomName(17),
      'field_business_phone[und][0][value]' => mt_rand(200, 999) . '-' . mt_rand(200, 999) . '-' . mt_rand(1000, 9999),
      'field_business_email[und][0][value]' => $this->randomName(17) . '@example.com',
      'field_business_website[und][0][value]' => 'http://' . $this->randomName(17) . '.com',
      'field_business_address_1[und][0][value]' => mt_rand(1, 9999) . ' ' . $this->randomName(12) . ' ' . $this->randomName(2),
      'field_business_address_2[und][0][value]' => 'Apt ' . mt_rand(1, 999),
      'field_city[und][0][value]' => $this->randomName(8),
      'field_state[und]' => 'HI',
      'field_zip[und][0][value]' => mt_rand(10000, 99999),
      'field_request_website[und]' => 'Yes',
);
$this->drupalPost('user/register', $edit, 'Create new account');

```

The code above successfully completes and posts the registration form.

How can I automatically approve and login as this newly submitted user for testing? Do I need to write tests to login the admin account, find and then approve the user?

---

**Additional Thoughts and Clarification:**

Looking at other options, can I somehow use `variable_set()` to accomplish the automated user approval above when the `setUp()` method is called?

# Answer
> 1 votes
While setting the user\_register variable works by automatically logging you in, if you want to test the default mail confirmation, you can inspect the mail as described over in your other question: How to inspect outgoing email content during a SimpleTest?.

Extract the link with a regex, "click" it by using drupalGet() and confirm by submitting the form (this is pretty much exactly what I did in the simplenews tests linked in the other question). Note that if you also want to be able to log in through the normal user login form after that, you need to load the user object and then set the pass\_raw property of the loaded user object to the password, because that is what is used in drupalLogin().

# Answer
> 1 votes
in the `setUp()` method I simply added: `variable_set('user_register', 1);`

This way I could `drupalPost` a new account and login immediately without approval.

`$this->drupalPost('user/register', $edit, 'Create new account');`

Account is successfully registered and the required additional fields were collected during registration.

---
Tags: testing
---


# Question
Title: How do you add taxonomy with fields to page--node.tpl.php?
I am trying to add to my node pages a taxonomy listing that includes fields I've added to the taxonomy. I'm able to add the field from the corresponding note into my page--node.tpl.php file with the following code:

```
<?php $field_country = field_view_field('node', $node, 'field_country');
     print render($field_country);
?>

```

Unfortunately this does not output the corresponding field I've attached to the taxonomy, which is an image field that contains a flag for the country.

Is there a way to print this field into page--node.tpl.php using Drupal 7 and no additional modules? It would be very useful to use these fields attached to taxonomy for more than just the taxonomy pages.

Thanks for the help!

# Answer
> 1 votes
This can be done without any need to use php code and tpl.php files. The capability to generate content based upon a taxonomy including images can be done by using the modules. These modules are intended to define and implement a site's design and are well written and tested. Template files will handle the layout and appearance of your content, but are not necessary for the content you have described. IF you are not familiar with Drupal, take a little time to learn more about what it can do before you make changes in the template files. If you are familiar with Drupal, then it might be helpful to understand more regarding what you are trying to do.

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


title: hook_menu_alter() with node URL alias

text:
# Question
Title: hook_menu_alter() with node URL alias
I have a node with ID equal to 60, which has a URL alias that is "mynodes/about-us." I would like to change the access callback of that node to `myfunction()`.

It doesn't work when I use the URL alias:

```
function celsis_forms_menu_alter(&$items) {
    $items['mynodes/about-us']['access callback'] = myfunction;
}

function myfunction() {
     return FALSE;
}

```

But it works when I use the node number:

```
$items['node/60']['access callback'] = myfunction;

```

How can I get the url alias to work and would it be possible to change the `access callback` for all nodes with alias starting with `mynodes/*`?

# Answer
> 2 votes
You cannot do that because when Drupal invokes `hook_menu()` and `hook_menu_alter()` the value contained in `$_GET['q']`, which is used to find the menu callback to use, has been already changed from the path alias to the normal path. drupal\_path\_initialize(), which is called by `drupal_bootstrap()` contains the following code:

```
  if (!empty($_GET['q'])) {
    $_GET['q'] = drupal_get_normal_path($_GET['q']);
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }

```

What you are trying to achieve can be accomplished in another way: implementing hook\_node\_access(). Differently from the equivalent hook in Drupal 6, it can be implemented also from modules that don't define a new content type.

```
function mymodule_node_access($node, $op, $account) {
  if ($op == 'view') {
    $path_alias = request_path();
    // ...
  }
}

```

`$account` contains the user object to which is being given access to the node. If the hook returns `NODE_ACCESS_ALLOW`, then the user has access to the node for the operation passed in `$op`; if the hook returns `NODE_ACCESS_DENY`, the user doesn't have access to the node; when it returns `NODE_ACCESS_IGNORE`, it leaves to other modules the decision.

request\_path() returns the path alias if one was used. This means that if the user is using a URL like example.com/node/60, it returns "node/60"; if the user is using example.com/mynodes/about-us, which is an alias for example.com/node/60, it returns "mynodes/about-us." In the case the user is using example.com/index.php, the function returns an empty string.

# Answer
> 2 votes
How about this? It's a bit of a simpler alternative. I'm guessing that you want the access callback to continue functioning even if you later create a new node and give it this same alias:

```
    function celsis_forms_menu_alter(&$items) {
      // Retrieve the Drupal system path for the page's alias
      $about_us_path = drupal_get_normal_path('mynodes/about-us');
      $items[$about_us_path]['access callback'] = 'myfunction';
    }

    function myfunction() {
      return FALSE;
    }

```

Note that if you do point this alias at a different node, you will need to clear the cache for this logic to keep working. `hook_menu_alter` is called when the menu is rebuilt.

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


# Question
Title: Problem on the comment form #validation and #submit
I've tried to create a validation and submit functions on a custom comment form, using drupal 7.9, but it's not working, and I don't know why.

In the following code, we can see the "dpm's" in the first function, but not the "dpm's" in the last ones.

```
function job_form_comment_node_job_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'job_comment_validate';
    $form['#submit'][] = 'job_comment_submit';
    dpm($form);
    dpm($form_state);
}

function job_comment_validate($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

function job_comment_submit($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

```

if I add a `#validate` or `#submit` it also doesn't call others drupal hook comments like presave, insert etc.

If I comment these lines, the hooks are called, but I can't use the validation or the submission functions in this case.

Do you have any idea on why this happens?

# Answer
You're missing `$form_id`, the third parameter of the function.

See `hook_form_alter()` reference on drupal.org. The problem you're experiencing might be a (weird) way of PHP reacting to that.

In situations like this you may want to check for errors on the logs (Drupal, PHP, MySQL). Some times there are useful hints there to figure what's wrong.
> -1 votes

---
Tags: comments, forms
---


# Question
Title: How to load a view with ajax so that additional js/css files needed by the view are also loaded?
Currently I'm using jQuery to load a view, like this:

```
$.ajax({
    type: 'POST',
    url: Drupal.settings.basePath + 'views/ajax',
    dataType: 'json',
    data: 'view_name=' + viewName + '&view_display_id=default&view_args=' + viewArgument, // Pass a key/value pair.
    success: function(data) {
      var viewHtml = data[1].data;
      target.children().fadeOut(300, function() {
        target.html(viewHtml);

        var newHeightOfTarget = target.children().height();

        target.children().hide();

        target.animate({
          height: newHeightOfTarget
        }, 150);

        target.children().delay(150).fadeIn(300);

        Drupal.attachBehaviors(target);
      });
    },
    error: function(data) {
      target.html('An error occured!');
    }
  });

```

My problem is, that for example if the view uses the 'Field Slideshow' module, the js/css files needed for it to work properly are not loaded. What could be a nice (= kittens unharmed) solution to this?

# Answer
Hmm, I feel like this question deserves a bigger bounty :-p but none the less here's my attempt at answering this.

Drupal already loads any extra css/js now I can't really find much documentation on it and sadly the JS files aren't easily documented without actually reading through the code but is there.

You really should try to avoid making $.ajax request yourself and instead wrapping everything with Drupal.ajax also if you use the Ajax System you don't even need to write the ajax request your self.

By implementing a proper Drupal ajax request using ajax commands most of the css/js handling will be done for you automatically.

By looking at your above code it looks like you you're making the same request views would normally do it self. So you should probably let views handled the ajax request and overwrite the ajax commands thats going to be fired to be your command. You can do this by either implementing a hook\_ajax\_comamnd\_alter but it kinda sucks with views because you loose all contextual information so I would recommend using hook\_views\_ajax\_data\_alter instead.

I know there's not much code in my answer, but it's hard to answer with code, being that the code currently there is not correct to being with.

For more information see Drupal.ajax in the misc/ajax.js file. For an example of implementing an ajax request with Drupal.ajax see the views ajax file. And if you want to see and example of views normal behavior being overwritten by changing the ajax commands see the views\_load\_more module where I do this behavior.

Also please feel free to comment on this answer, if anything here is unclear.

On and for more info on the Ajax Framework see Ajax Framework for example see the example module, even thought most of what you want to do is not cover in the examples module.
> 7 votes

---
Tags: 7, views, ajax, javascript
---


# Question
Title: Behavior not attaching to a form element
I have a module for relating pieces of content to each other. My module successfully adds a field to all content-types that is essentially a list of integers, meant to hold node ID's. I want AJAX functionality such that when the user begins typing the title of a node, autocomplete suggestions begin appearing. I've already implemented the web service via Drupal to retrieve nodes based on partial titles, and that's working very well. The problem is now attaching the behavior I want to the form element.

Two problems:

1) No way to uniquely identify the form element in question. The class name is not going to be usable if there are more than one of them, which there may be. How can I force a unique class name? Something like class="content-relation" for each one?

2) The behavior I want to attach is failing to do so. I've tried a couple different ways...here they all are.

Way 1:

```
Drupal.behaviors.content_relation =  {
    attach: function(context) {
        jQuery('input.form-text').change(function() {
            var ul = jQuery('<ul />')
                .css({position: 'absolute', top: '0px', left: '0px'});

            jQuery.get(
                '/api/'+jQuery(this).val(),
                function (data) {
                    jQuery.each(data, function(item){
                        var li = jQuery('<li>');
                        li.html(item.title);
                        li.appendTo(ul);
                    });
                }
            );
        });
    }
};

```

Way 2:

```
jQuery.ready(function(){
    jQuery('input.form-text').live('change', function() {
        var ul = jQuery('<ul />')
            .css({position: 'absolute', top: '0px', left: '0px'});

        jQuery.get(
            '/api/'+jQuery(this).val(),
            function (data) {
                jQuery.each(data, function(item){
                    var li = jQuery('<li>');
                    li.html(item.title);
                    li.appendTo(ul);
                });
            }
        );
    });
});

```

...but none of the inputs with a class of form-text have this function listed in their change-listeners, nor do they respond to changes. Thoughts?

# Answer
You shouldn't need a single line of JS to have autocomplete textfield working in D6/D7. Please see the Form API refrence.
> 1 votes

# Answer
It's probably not possible to have a unique class name, especially since that is the job of the id attribute. The name of your field will def be unique as it matches the array you defined in your form alter.

The change event on text boxes is only fired when the value of the box has changed and it loses focus. For autocomplete you probably want it to give suggestions on each keystroke, the change event will not do this.

Have you looked at the autocomplete functionality that is built into the forms api? There is a good write up at http://timonweb.com/how-create-ajax-autocomplete-textfield-drupal-7 and more info at http://api.drupal.org.
> 0 votes

---
Tags: nodes, ajax, javascript
---


# Question
Title: ahah_helper or ctools for ahah in Drupal 6?
The excellent ahah\_helper module (http://drupal.org/project/ahah\_helper) improves the core ahah functionality to the point where it works quite nicely.

Ctools (http://drupal.org/project/ctools), seems to bypass the core functionality totally, offering its own brand solution.

Ctools seems to be quite a bit more complicated, needing more complexity to deal with no-js situations : http://drupal.org/node/1025448#comment-4196882

Where as ahah\_helper seems much cleaner/simpler to deal with : http://drupalcode.org/project/ahah\_helper.git/blob/refs/heads/6.x-2.x:/ahah\_helper\_demo.module

So.

Which is better? Which is more like the implementation in 7 (so we only learn once)?

# Answer
> 1 votes
You're better of using ctools in D6. Also all the ctools ajax implementation is whats in Drupal 7 known as the Ajax Framework

---
Tags: 6, forms, chaos-tool-suite, ajax
---


# Question
Title: Facebook Style 'Read More' instead of standard Pager in QuickTabs?
I am using Quicktabs to display a few views (grid style). At the bottom I am using the standard Pager that comes with QuickTabs. Is it possible to replace that with a 'Show More' link (ajax style?) Example would be at the bottom of a Facebook Wall, or here- http://gdgt.com/answers/

Thanks for the help!

# Answer
> 3 votes
You can use Views Infinite Scroll.

> Views Infinite Scroll provides a pluggable pager that enables Views infinite scrolling by using jquery.autopager plugin. Using this module with Views page display will load another page whenever the user reaches the bottom of the page.

# Answer
> 1 votes
I would say Views Load More but there's a more thorough answer over at Load more content with ajax when clicking more link in a view with a comparison of all the views plugin that implement this feature.

---
Tags: ajax
---


# Question
Title: How do I reinstall the Forum module in Drupal 7?
I did something really stupid: I deleted the taxonomy\_forum field (Forums) from the content type. Now I'm get all sorts of errors.

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'flo1121202154643.field\_data\_taxonomy\_forums' doesn't exist:
> SELECT field\_data\_taxonomy\_forums0.entity\_type AS entity\_type, field\_data\_taxonomy\_forums0.entity\_id AS entity\_id, field\_data\_taxonomy\_forums0.revision\_id AS revision\_id, field\_data\_taxonomy\_forums0.bundle AS bundle FROM {field\_data\_taxonomy\_forums} field\_data\_taxonomy\_forums0 WHERE (field\_data\_taxonomy\_forums0.deleted = :db\_condition\_placeholder\_0) AND (field\_data\_taxonomy\_forums0.bundle = ..........

How do I reinstall the Forum module in Drupal 7 from scratch (including recreating the database schema)?

# Answer
To uninstall a module, you follow these steps:

1. Deselect the checkbox shown for the module in admin/modules, and click on the "Save configuration" button at the bottom of the page
2. Select the "Uninstall" tab (admin/modules/uninstall), and in that page select the checkbox shown close to the name of the module you want to uninstall ("Forum")
3. Click on the "Uninstall" button
4. In the next page, click again on "Uninstall"

When you execute the first two steps, you are only disabling the module, which is not yet uninstalled. It is when you execute the last two steps that you uninstall the module.

To re-install it, you need to:

1. Return to the page listing all the modules (admin/modules)
2. Select the checkbox shown for the module you want to install ("Forum")
3. Click on the "Save configuration" button at the bottom of the page

Uninstalling a module should already clear the cache, but to be sure you can manually clear the cache before to re-install the module.
Once the module is uninstalled, installing it back will let Drupal create the database tables used by the module again. The same tables are deleted from Drupal when the module is uninstalled.

I noticed a little issue that happens when you uninstall and re-install the Forum module: The default taxonomy term used by the module is created again all the times you re-install the module, and it seems it is not removed when the module is uninstalled. This is the result of uninstalling and re-installing the module more than once; each time the taxonomy term is created, even if it was already present.

Actually, it is not even required to uninstall, and re-install the module; it is enough you disable, and then re-enable the module, as the code that creates the missing field is not contained in forum\_install(), but in forum\_enable(), which the function executed when the module is enabled.

I was going to suggest a different way to resolve this issue, and which consisted in manually creating the missing field, but I noticed it doesn't work. The problem is that the module that allows to create a field through the user interface always add "field\_" at the beginning of the field names for the fields you create, but the field created from the Forum module doesn't have that prefix; the result is that some database tables and a field present in a table don't have the name the module is expecting, and the module throws errors.
> 4 votes

# Answer
Uninstall the Forum module and clear all cache, then install forum module make the same content type with same fields and add some data into it. Now try over with Views, and see if it is working or not.
> 0 votes

---
Tags: nodes
---


title: Changing the User Title

text:
# Question
Title: Changing the User Title
I did some searching here, but I couldn't find exactly what I was looking for. Is there a template.php function that I can add to change the content title (not the `<head>` page title) of a user to be a field created after-the-fact (like a first name or the last name field)? If it can't be a function, maybe some type of 'if' statement to wrap around the content title output to check if it's a user page and then output the fields would probably work.

# Answer
> 5 votes
Try the Real Name module, it's worked very nicely for me. Here is a quote about it (from the module's project page):

> ... allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook\_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.

# Answer
> 6 votes
The page title of the user profile page (like example.com/user/1) is generated by format\_username(). If you want to control the username everywhere it occurs in the site, you can implement hook\_username\_alter in a custom module.

If you just want to change title on the user profile page, you could add THEMENAME\_preprocess\_page to your template.php to override `$variables['title']`. An example (untested code):

```
<?php
/**
 * Preprocess function for page.tpl.php.
 * Replace 'THEMENAME' with the name of your theme.
 */
function THEMENAME_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is a number and the third part is empty.
  $arg = arg();
  if ($arg[0] == 'user' && is_numeric($arg[1]) && empty($arg[2])) {
    // Do stuff to create the desired username and set the $title variable for the template.
    $variables['title'] = $variables['firstname'] . ' ' . $variables['lastname'];
  }
}
?>

```

---
Tags: users, 7
---


title: Zen header 'site name' + links issue

text:
# Question
Title: Zen header 'site name' + links issue
I'm using a Zen sub theme, and I've placed the main menu block into the header.

I would like to place the links to the right of the site name, but they only sit underneath. I've tried playing with the CSS styles that control the menu block, without success.

Is there a special trick of Zen's quirk I'm missing?

# Answer
> -1 votes
I am new to coding so anyone should feel free to correct are add to this.

Your theme is placing the content on a page using a file called page.tpl.php. It may be found in your subtheme folder or in the parent them folder. This file is responsible for assembling the HTML code that actually displays your page. The file is a text file and is easy to open and edit (not as easy to understand if you are not familiar with HTML and PHP. I am using Fusion themes, so there may be some difference, but if you search for 'menu' you will find the part of the template that generates the menu. There you will probably find a HTML command to 'clear' or a Class definition that will include the clear command. This command is telling the browser to push further content in the region, such as your block, to the next row. To change this you will need to make an override page.tpl.php file (copy the parent theme file into your subtheme directory and remove the command. If the command is in the CSS file, you will have to alter the CSS file containing the class definition.

I do not recommend doing this if you are not yet familiar with coding in Drupal (do a bit of research first). Good luck.

---
Tags: theming, navigation
---


title: where is D6's statistics_counter in D7?

text:
# Question
Title: where is D6's statistics_counter in D7?
I want show the number of views count in node.tpl.php with Drupal 7, but I cant find the Drupal 7 Equivalent of statistics\_counter.

where can I find it?

# Answer
> The **Statistics** module shows you how often a given page is viewed, who viewed it, the previous page the user visited (referrer URL), and when it was viewed.
>
> In Drupal 7 configure statistics via **configuration \> statistics**.
>
> To enable collection of statistics, the ***Enable access log*** checkbox on the Statistics settings page must be checked.
>
> Enable ***Count content views*** to turn on and off the node-counting functionality. If turned on, an extra database query is added for each node displayed, which increments a counter.

Make sure you set permissions for the module at admin/user/permissions and configure it.

Based on drupal.org and http://groups.drupal.org/node/147619
> 2 votes

---
Tags: 7, theming, nodes
---


# Question
Title: How do I pass a variable from a custom module to its template file?
I need to know the simplest method to pass variable from custom module to its template file. I have created the custom.module and placed custom.tpl.php in the module folder.

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

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

  return $items;
}

function custom_page() {

    $setVar = 'this is custom module';
    return theme('custom', $setVar);
}

```

i have added theme function but it is not working, can any one suggest me what is wrong with this code

```
function theme_custom($arg) {
  return $arg['output'];
}

function custom_theme() {
  return array(
    'Bluemarine' => array(
        'variables' => 'output',
        'template' => 'Bluemarine',
     ),
  );
}

```

# Answer
Independently from the Drupal version for which you are writing the module, there are two errors in your code:

* You define "Bluemarine" as theme function, but then you call `theme('custom')`, which would call the "custom" theme function
* If you define "custom" as a theme function that uses a template file, then `theme_custom()` is never called

If you are writing code for Drupal 6, then the code should be similar to the following one. I take the assumption the name for the theme function is `custom`.

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

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

  return $items;
}

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

function custom_page() {
    $output = 'This is a custom module';
    return theme('custom', $output);
}

function theme_custom($output) {
}

```

The template file will have access to `$output`, and to any variables set in `template_preprocess_custom()`, if your module implements it.

For example, you could implement code similar to the following one:

```
function template_preprocess_custom(&$variables) {
  if ($variables['output'] == 'This is a custom module') {
    $variables['append'] = ' and I wrote it myself.';
  }
}

```

With this code, the template file has access to `$output` and `$append`.

As example of theme function that uses a template file, you can look at theme\_node(), which is defined in node\_theme(), and that uses node.tpl.php as template file; the preprocess function implemented by the Node module for that theme function is template\_preprocess\_node().
> 7 votes

# Answer
You are calling the wrong theme function. Instead of `function theme_custom` it should be `function theme_Bluemarine`. You also need to pass an array to the variables piece of hook\_theme(). See a simple example here.

Using your example (after changing template and theme function to `custom`):

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

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

  return $items;
}

function custom_page() {
  $setVar = 'this is custom module';
  return theme('custom', array('output' => $setVar));
}

function custom_theme() {
  $path = drupal_get_path('module', 'custom');
  return array(
    'custom' => array(
        'variables' => array('output' => null),
        'template' => 'custom',
     ),
  );
}

```

Now in custom.tpl.php just need `<?php print $output; ?>`
> 4 votes

---
Tags: theming
---


# Question
Title: How can I play an already uploaded video inside an Amazon S3 bucket? And how can I use the String Authentication on it?
I´m new with video module, and with Amazon S3. I need a video (that I´ve **already uploaded** to an Amazon S3 bucket), to be able to be played inside my site. I don´t want to upload it again through Drupal.

This video needs to be **private**. I´ve read something about "**S3 Query String Authentication**" but didn´t get how to actually implement that in my site.

I´m not able to point to a video that´s already uploaded to a bucket. I can only upload through Drupal, or upload it to a folder inside my drupal installation. How can I just grab the video?

And Should I do that using string authentication? How can I avoid people that´s not logged in to see or link to the video? (I know that there´s no way to stop other people to copy your stuff, but I´ve read about hot links and would like to avoid that from happening if I can).

I need that video to be available for a long period of time for my users, I just don´t want them to post the link in other sites (and use my bandwith).

I´m pretty clueless. Please I would love some help if you can. Thanks!!!! Rosamunda

# Answer
> 1 votes
I'm answering this, hoping I can help anyone else with the same problem. If you're trying to play videos already uploaded to your S3 Amazon account, you won't find an appropriate Drupal Module to do so. (see this). What I did is to get myself an Amazon Cloudfront account and protect the videos manually with an expiration date; then I pasted the video (using the player jwplayer), and I controlled the access to that node using any of the node access modules.

---
Tags: files
---


# Question
Title: Does deleting a field in a content type remove the data?
A previously posted question appears to assume that the data is deleted in the database if the field is deleted in his/her forum content type. I think that the field still exists and the data is still available if you add the field back. I am reluctant to test this out on my current website in case I am wrong :}.

# Answer
Deleting the field deletes the data too.
As far as I can see, the database tables used to contain the field data are renamed, but they are emptied.

Visiting the page at admin/structure/types/manage/forum/fields, I deleted the "Forums" field used for the "Forum" content type; this is what I see watching the content of the database used for my Drupal test site, after I removed the field.

To notice also that the "deleted" column in the "{field\_config\_instance}" table is set to 1 for deleted fields.
> 2 votes

---
Tags: entities, database, nodes
---


# Question
Title: How can I make this with the Views module?
I am trying to find out how to make a view which, in pseudo code, does this:

> If year = 2005 and month = 04 and page = 2 then display 2 articles

I have Views3 installed, but I can't find out how to make the date filter, and how to make the page filter.

# Answer
> 1 votes
How to show only oldest and newest node in Drupal views?

Check this out, I believe you will definately get answer with views, contextual filters. and with the content type = Article and display only 2 with help of PAGER..

Extended answer

And when select that option, you will get another pop like below image

After making up a selection, write how many items you want to display.

And if you want to add see the month, why you just add fields to display. also add a content posted date field below image will help out

# Answer
> 1 votes
As @JoeS instructed, you likely can accomplish what you want simply by limiting the number of posts per page to 2 and ordering by chronology.

If however, you did want to show the only posts for April, 2005 with two posts per page, you could pass the values through the URL and use two contextual filters to display the posts that match.

First add the Contextual filters for "Content: Created month" and "Content: Created year"

Then configure the filters to use the default values from the URL, or by matching values from the current Date

# Answer
> 0 votes
I am not clear about what you are doing with the page=2 then show 2 articles. Are you referring to the second page of the view? Are the 2 articles the first two results of the view? Could you please clarify the question a bit?

When you define a view to select certain articles you set the limit for how many appear on the display first page. The page gives the user the means to access any additional results. The order of the results is set by the sort settings. IF you want specific articles to appear on a specific page of the view display you must address the order they are sorted. (You could add a number field to the articles to set the order you want and then sort by the field value).

Looking at your view settings, I believe your path is incorrect. The path setting is the name of the URL for the view. Give it a name such as /blog/blogtype/(# or name). Your filter settings will select only blogs as set. If you want to filter further then change the path to blog/blogtype/% and use a contextual filter to get what you want. (There is much to learn to use views effectively. I recommend you check out the video series "taming the Beast' at nodeone.se to get a handle on how it works.

---
Tags: views
---


# Question
Title: How to read JSON from external URL and display in a block?
I want to load some JSON data from an external URL and display it in a block.

How do I go about that?

# Answer
> 7 votes
For the most basic solution, you would need to:

A more complex version of your custom module could for instance involve implementing hook\_block\_configure to make the URL configurable from the UI, using theme functions to generate the HTML output, and caching/storage of the return value.

A completely different approach, which may or may not be appropiate in your case, would be to use the Feeds module to retrieve the JSON and store the data as nodes, and use the Views module to generate a block listing those nodes.

# Answer
> 2 votes
Maybe too simple of an approach, but if all you truly want to do is display JSON data (no need to store it), then I'd add a new block as "Full HTML" and then add some JQuery.

To embed an HTML snippet it would be:

```
<script type="text/javascript">
(function ($) {
$(document).ready(function(){
  $('#remoteFeed').load('http://example.com/path/to/page #some-div-id');
});
})(jQuery);
</script><div id="remoteFeed"></div>

```

The method would be similar for JSON, only you'd have to do some formatting of the return that would be custom to your application.

Here's a working example pulled from JQuery.getJSON documentation customized ever so slightly to work inside a Drupal Block:

```
<script type="text/javascript">
(function ($) {
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "awesome",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#flickr-images");
      if ( i == 3 ) return false;
    });
  });
});
})(jQuery);
</script>
<div id="flickr-images"></div>

```

---
Tags: 7
---


# Question
Title: Will URLs with spaces in the path work on all major browsers?
Will a path to content such as `example.com/content type/page name` work? or must it have a filler such as dashes - `example.com/content-type/page-name`?

# Answer
Spaces should be at least encoded as **%20** .

It's not a good practice, not a standard, to use spaces in URLs at all. In my opinion it is better to replace all spaces with dashes or to concatenate them.

Spaces will cause problems with links, for example you might get:

instead of:
> 4 votes

---
Tags: 7, uri
---