title: Multiple vocabulary terms filter?

text:
# Question
Title: Multiple vocabulary terms filter?
I have a vocabulary called category, another vocabulary called author and the content type is videos. I want to display all the authors(unique) by category vocabulary term?

Can any one please suggest me how to achieve this using views?

# Answer
> 1 votes
I ran into a similar situation and hacked up a solution based upon the advanced solution here: http://drupal.org/node/770782.

Addition per commentary...

Basically what I was running into here was a situation where I had node content tagged with a genre as well as a location and what I wanted was a list of all the genres in a location.

A quick description of the view would be "Filter on published content of node type X with an argument (Drupal 6) (now Contextual Filter in Drupal 7) of location and display the genre field of each found."

A difference in my solution is that I kept count of how many nodes were tagged and I sorted on that while in the link given above it was sorted alphabetically.

Doing this with Views created lots of duplicate rows obviously because it was listing each node it found with that genre.

So, basically what I ended up doing was going into hook\_views\_pre\_render() and looping through the results and removing all duplicates, eg:

```
function YOUR_MODULE_views_pre_render(&$view) {

  if ($view->name=='THE_NAME_OF_THE_VIEW_YOU_ARE_LOOKING_FOR') {

    drupal_set_message('<pre>' . print_r($view->result) . '</pre>'); // to get the correct $result->FIELD_NAMES for your particular View

    // what we are first going to do is go through the results of the View
    // and create an array of unique taxonomy ids that we find.
    // we are going to store that info in array $unique_tids
    // we are also going to keep a count so we can sort on "popularity"

    $unique_tids=array();
    $count_tids=array();

    foreach($view->result as $r => $result) {
      if ($result->term_data_vid != 'THE_VOCAB_WE_ARE_LOOKING_FOR' ) { // looking back, I probably could improve the View substantially by filtering on just one taxonomy vocabulary :)
        unset($view->result[$r]);
      } else {
        $count_tids[$result->term_data_tid]++;  // keep count of how many times we see this tid
        if(in_array($result->term_data_tid, $unique_tids) || !$result->term_data_tid) { // if we have already seen this tid, or it does not exist, delete this row from the results
          unset($view->result[$r]);
        } else { // we haven't seen it, so keep it in the View results
          $unique_tids[] = $result->term_data_tid;
        }
      }
    }

    // at this point we could just return and our View would contain the
    // unique genres, but it would be "sorted" based upon the order in which
    // the node it was first tagged in was created (I think) but we want to
    // get fancy and sort this listing with the most popular genres first
    // based upon how many pieces of content has been tagged with it, so...

    arsort($count_tids); // sort the counts in reverse order so the largest counts come first
    $new_result=array();

    // crude but effective ... curse you for making me look at years old bad code :)
    // but basically go through the counts and find the Views row that corresponds

    foreach($count_tids as $c => $count) {
      foreach($view->result as $r => $result) {
        if ($result->term_data_tid == $c) {
          $new_result[]=$result;
        }
      }
    }

    // we now have our unique results in the order we want so set
    // the View to it...

    $view->result=$new_result;

  }

  // any other pre_render()ing goes here...

}

```

And that's what I did to present unique genres in a location sorted by how many pieces of content were tagged with a particular genre. Let me know of any/many typos in the code (I had to clean out a lot of extraneous code to get it down to the basics) and or if you would like any other explanations. Also looking back (I wrote this in my nube stages of Drupal) I can clean up a lot of it. Thanks Drupal Answers for making me go back and rewrite totally working two year old code the right way :)

Oh, looking at comments in my code, this created havoc with paging so in my system I just listed everyone on one page since I didn't have all that many genres to worry about. I *think* if you did this in hook\_views\_post\_execute() instead it would respect paging.

---
Tags: taxonomy-terms
---


# Question
Title: How do i create node directly from my own module with data of my tables
I need create a node from one table of my Database of drupal with all rows that it have.

That is, I need to extract data from my table and insert them automatically and make it appear as a node. Everything from my own module (That is, when I turn on my module see my table data were converted to node).

I thought of 2 solutions for this. The first is to create the content type in my drupal site and from my module implement "form\_submit". (Can you do this?). The second (which I am trying to do) is to create my type of content and form from my module. And since I can do the integration and transformation node me on my table.

Does anyone can help me on how I can do this? A code example of how to extract data and insert them into my form and make a submit directly?

thanks

# Answer
From the information you provided I would handle this the following way:

1. Create a custom content type via the GUI with all the fields that you need.
2. Create a custom module and register a path via hook\_menu(). I would set `'page callback' => 'drupal_get_form'`, `'page arguments' => array('mymodule_create_content_form')` and `'access callback' => 'mymodule_admin_restriction'`. `mymodule_admin_restriction` would be a function to allow access to user 1 only. `mymodule_create_content_form` would be a custom form builder function with just a submit button.
3. In the form submit handler I would then write code to extract data from the database and create new nodes from it. The easiest way to get data out of your database would probably be with db\_query().
4. For programmatically creating nodes you could use either node\_save() or drupal\_execute(). The first one is a quicker option while the second one more closely mimics normal node creation by invoking additional hooks. You should be able to find a solid amount of information about them on the web (for example here, here and here).

This approach should be fairly good to get started with. Once you get the whole thing working without errors (in your development environment) you could move the code to your module's install file's hook\_install() and maybe even programmatically create the new content type there if needed.
> 1 votes

---
Tags: 6, nodes
---


title: Taxonomy view doesn't display products

text:
# Question
Title: Taxonomy view doesn't display products
This is the situation.

I have a product type and in this type i use a term reference field. Then i add some products. Next step, i create the product displays using the product reference field (the default one). So far so good. Then i use views and enable the build in view for taxonomies which in non commerce site shows the nodes for each taxonomy. Now it displaying nothing. I tried to add the product relationship but still nothing.

Any ideas?? Thank you

# Answer
> 0 votes
1. Do you have the devel themer enable? I have the problem with some filters lately..it was not displaying the filter. The problem was that I have the devel themer enable..
2. Are you using ubercart or commerce? if you are using commerce make sure to have associate the taxonomy with the display..here it is a little reference, that video helped me with my taxonomy and give me the right path Building a Drupal commerce catalog

---
Tags: views, taxonomy-terms, commerce
---


title: Get page content from page-title

text:
# Question
Title: Get page content from page-title
Is it possible to get page content (in array) from for example a Title. Like this;

```
$wantedPage = function_to_get_page_content('This is the title');

```

and then just `print_r($wantedPage)` to get this page content, in array.

I'm pretty new on this great CMS-system..

# Answer
> 0 votes
If what you mean is the node contents, in D6, this would be as easy as `$node = node_load(array('title' => $text));` and I would hope the same holds true it D7, but I've been known to misspeak a bit there :) Just realize that titles aren't necessarily unique. If you mean the page, with all the header, footer, css, js, blocks and so forth, that's another story in of itself.

---
Tags: 7
---


# Question
Title: Repeat view entry for each value of multivalue field
I am using commerce module in D7. Each order can have a single line item, but you can have whatever quantity you like in that line item. For each item of this quantity I store a text value that is held in a multivalue text field on the list-item itself.

So you have:

> Product 1 Quantity 1 Price $10 Information: Item1Text
>
> Product 2 Quantity 3 Price $10 Information: Item1Text, Item2Text, Item3Text

I would like to have a view for each order to display each item of the line item as a separate entry. So for example:

> Product 2 Price $10 Information: Item1Text
>
> Product 2 Price $10 Information: Item2Text
>
> Product 2 Price $10 Information: Item3Text

Is this at all possible, because I have tried all the tricks that I know, but cannot produce such a view. The reason I need something like this is that I can have a separate invoice for each of the items included in the order, besides them being purchased together. So if you buy 3 balls, I would create 3 invoices each describing the purchase of a single ball.

# Answer
Ok I finally figured out how to do this.

I order for the line item to repeat itself I unchecked the single line representation for multivalue field.

And in order to repeat the whole invoice I call a view from within another view.
> 0 votes

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


title: htaccess style login for drupal

text:
# Question
Title: htaccess style login for drupal
I want a separate login for my site for Drupal. One to simply access the page, the same functionality that an .htaccess login would provide.

Except I want it to be styled as a separate html page, not as the default module popup htaccess does.

Is there a Drupal module for this or do I need a simple PHP script outside Drupal.

# Answer
The Secure Site module could be the best choice:

> This module allows you to authenticate users with a browser-based password (HTTP Auth). You can restrict access to the site by role and choose to secure restricted pages or the entire site. This means the site will be inaccessible to search engines and other crawlers, but you can still allow access to certain users.

You can change the settings to use a page instead the popup. It's also possible to theme the login page - see the information here.
> 3 votes

# Answer
The Protected Node module allows you to optionally set passwords on nodes.
> 1 votes

---
Tags: 7
---


# Question
Title: image field - how to overwrite existing image?
How to set up the image field in a content type so that it always **overwrites** images with the same name instead of creating new images with name suffix \_0, \_1 etc. Currently, while editing a node and uploading image with the same name as existing one, it won't overwrite.

If it is impossible, then how to achieve it programmatically (hook, hack?) without help of any additional modules, just using the core image field.

# Answer
> 3 votes
Its not there -- this functionality has been discussed on Drupal.org and ruled out by the maintainer of the filefield module before because it could cause the original file to be deleted before the node is saved. You can follow their argument here:

http://drupal.org/node/427212

Fortunately, if you do want the file to be replaced when you upload a new one with the same name there is an alternate module you can add for 6x/7x called Upload File Replace that does this and avoids the issue above:

http://drupal.org/project/upload\_replace

---
Tags: 7, nodes, entities, media, files
---


# Question
Title: where is the source code for "Powered by Drupal"
Someone told me the footer text "Powered by Drupal" in Drupal7 is provided by `theme_system_powered_by()`, which is turned into a block by `system_block_info()` and `system_block_view()`. I wonder in what file(s) these functions can be found. Thanks a million.

# Answer
> 7 votes
Here's the API documentation for all your needs:

Also, please note that modifying the output of `theme_system_powered_by()` should be done using a theme hook from your theme code. If you wonder how to achieve this, this might be a relevant article for you.

# Answer
> 2 votes
All the functions are defined in the system.module file, at the following lines:

* `system_block_info()`, line 2021
* `system_block_view()`, line 2053
* `theme_system_powered_by()`, line 3387

This information is normally not useful, as the code of those functions (as other Drupal functions) is visible on the API reference site. The core modules should not be edited.

---
Tags: theming
---


# Question
Title: why is the node id missing from the comment:edit action?
When I setup a trigger on comment creation and edit that fires the action "send email" I have the folling tags available in the action editor that seem to be missing the nid on output:

```
[comment:edit-url]
[comment:url]
[comment:url:absolute]

```

This gives me the following output in emails

```
http://example.com/comment//edit
http://example.com/comment/#comment-
http://example.com/comment/#comment-

```

Is this a flaw in the D7 or and I not doing it right?

Thanks in advance for any insights.

# Answer
> 1 votes
@Denford: You are right in saying that comments do have ids. They are just called cids and not nids :-)

What is the trigger that you are firing? My guess is that for a new comment posted, you are not seeing the 'cids' because they would be available only to the trigger 'after saving a new comment' and not the trigger 'when either saving a new comment or updating.. blah blah'.

# Answer
> 0 votes
I may be wrong, but I don't believe comments are considered "nodes" in the traditional Drupal sense.

The terminology is in flux, but traditionally nodes refer to pieces of content.

I believe comments now fit into the scheme as an entity, as just about everything else in Drupal now does.

This ambiguity is sort of an issue now with the advent of the entity system.

---
Tags: comments, emails, actions, rules
---


# Question
Title: Changing form field title within hook_preprocess_form() does not work
I have customize drupal user registration form which I want to change some field titles.

I implemented hook\_preprocess\_form() within theme and changed titles of some form fields, but it didn't work.

While debugging I found that it has '#children' item already there with rendered HTML inside it. Then I tried to change that value by using drupal\_render\_children(), but that also doesn't work.

What is the right way?

# Answer
Use `hook_form_alter()` to change the form before it gets rendered.
> 1 votes

---
Tags: 7, hooks, theming
---


title: Move file in Drupal 6

text:
# Question
Title: Move file in Drupal 6
I am using drupal 6 as i am trying to save file that comes from another server through Json format

I am using

```
file_move('path of image','sites/default/files');

```

I also tried this one Still having same error

```
file_move('path of image','sites/default/files', $replace = FILE_EXISTS_RENAME));

```

But it gives this error

> Fatal error: Only variables can be passed by reference in

How to solve this? Anybody have idea ?

Thanks

# Answer
> 2 votes
Your First argument must be a variable. The `file_move()` documentation says:

> `$source`: Either a string specifying the file location of the original file or an object containing a 'filepath' property. This parameter is passed by reference and will contain the resulting destination filename in case of success.

---
Tags: 7, files
---


# Question
Title: Module for form submitting straight to admin section
Can anyone recommend a module for a contact form to submit to the administrator (so the administrator can view/read it)?

Users should be able to anonymously submit messages; they should not first log in, or create an account.

# Answer
You should use the Webform module.

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
> 1 votes

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


title: XML to node in Drupal 6

text:
# Question
Title: XML to node in Drupal 6
I am using the Services module, through which I have created XML.

But i want to import this XML data into another drupal website. It contains images too.

I also installed feeds module but don't have idea how to use this.

# Answer
You need to get an XML parser module that interacts with node inserts, similar to feeds xml I would assume. This should allow you to insert the data into your db.
> 1 votes

---
Tags: 7, taxonomy-terms, feeds
---


# Question
Title: Passing parameters from Panel to View (contextual filter)
I ran into a little problem today, I have a specific panel for all my products. This panel contains out of a 3 column layout.

One of those columns contains a list of all other products in the same category. (which is a view).

When I created the view, I added a contextual filter to only display products out of the category that was send. (Categories are nodes and linked by a node reference) (This is just to allow the client to easily add and remove categories so he doesn't have to use the build in taxonomy)

I noticed however that I can only use the node id of the category to filter.

The problem is that the Panel only sends the string to the View, so the filter doesn't work. Is there a way to get the node id of the linked category?

# Answer
General solution:

1. Your View should have a "Content pane" display
2. Your pane should be configured to require an argument that matches the one your contextual filter wants.
3. Add the pane to your page.

For your specific question, I don't understand how you pass a string at all to Views, so I need more info about your setup to be more specific.
> 2 votes

---
Tags: views, panels
---


# Question
Title: D7: function calls too early (before DOCTYPE) and mess my page
I have included a class file in my module:

```
function MYMODULE_init() {
  require_once(drupal_get_path('module','MYMODULE')."/jcart/jcart.php");
}

```

where I declare a function

```
public function display_container(){

  echo "<div id='jcart' class='jcart1'>";
  echo "</div>";
  echo "<div id='jcart-tooltip'></div>\n";

}

```

I called this function in another module (they are all the same level default/modules)

The problem is this func displays its content before the html doctype causing the layout to mess:

```
<div class='checky'><div id='jcart' class='jcart1'></div></div><div id='jcart-tooltip'></div>
<!DOCTYPE html>

```

# Answer
You need to return your HTML string as the page callback rather than outputting it directly...otherwise what your doing is incompatible with the the Drupal theme system, and is why you're getting the problem you're getting at the moment.

Without seeing all of your code its impossible to debug this completely but suffice to say that in whichever page callback function you're calling `display_container()` you want to do this instead:

```
// Start the output buffer
ob_start();

// This will perform the echo to your new local buffer, not the screen buffer.
display_container();

// Get the temporary buffer content into a variable.
$output = ob_get_clean();

// Return the page callback to Drupal as normal
return $output;

```

If you're in a block view (which I seem to recall you might be from one of your previous questions) that last line would be:

```
$block['content'] = $output;

```

The other, perhaps simpler method here, would be to simply change your `display_container()` function to return the string rather than output it directly:

```
public function display_container(){
  $container = "<div id='jcart' class='jcart1'>";
  $container .= "</div>";
  $container .= "<div id='jcart-tooltip'></div>\n";

  return $container;
}

```
> 3 votes

---
Tags: 7
---


title: Limit the Link field to certain domains

text:
# Question
Title: Limit the Link field to certain domains
I'm looking for a module that will let me limit users to certain domain names when they edit a Link field.

For example, only let users enter a URL if the domain name is `facebook.com`, `twitter.com` or `plus.google.com`.

This list must be easily editable by admins.

Does such a module exist?

(Also: See my other question, if there is some a module that can do both it'll be great)

# Answer
> 1 votes
You can use the Field Validation module

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.

From there you could a custom PHP function/regular expression to match the URLs against the field value.

This will only editable by admin in the sense that they can also edit the PHP code/regular expressions in the field validation rule. I'm not aware of a specific module that will do everything that you want without any customisation.

---
Tags: 7, entities, navigation
---


title: DraggableViews questions

text:
# Question
Title: DraggableViews questions
If I followed the README.txt in the module and created a view with a sorting field as instructed, should I be able to drag the items around with a four-way cursor, and then Save? I do see the Save button, but no ability to drag...

Also, is there a way to have DraggableView come into play for a view which uses display mode (teasers) rather than fields? (I do have my own CCK field named "weight", which I could make use of and get away without DV, so it's just a question of how to make admin UI easier).

# Answer
> 1 votes
1. Yes, you should get the four-way cursor and be able to drag stuff around. My own experience has been that DW for D7 is quite buggy. We use a particular commit in NodeStream's makefile, you could try to work from that one, as we do our best to keep well working versions in that make file.
2. I don't think you can use a View mode, but must use fields. I could be wrong though.

---
Tags: views
---


# Question
Title: change breadcrumb separators while Omega subtheme
How do you change breadcrumb separators when using Omega subtheme? I tried the usual breadcrumb hook, but it didn't work.

# Answer
> 2 votes
Lances answer was right, but just in case I'll put the code here.

```
function theme_delta_blocks_breadcrumb($variables) {
  $output = '';

  if (!empty($variables['breadcrumb'])) {
    if ($variables['breadcrumb_current']) {
      $variables['breadcrumb'][] = l(drupal_get_title(), current_path(), array('html' => TRUE));
    }

    $output = '<div id="breadcrumb" class="clearfix"><ul class="breadcrumb">';
    $switch = array('odd' => 'even', 'even' => 'odd');
    $zebra = 'even';
    $last = count($variables['breadcrumb']) - 1;

    foreach ($variables['breadcrumb'] as $key => $item) {
      $zebra = $switch[$zebra];
      $attributes['class'] = array('depth-' . ($key + 1), $zebra);

      if ($key == 0) {
        $attributes['class'][] = 'first';
      }

      if ($key == $last) {
        $attributes['class'][] = 'last';
      }

      $output .= '<li' . drupal_attributes($attributes) . '>' . $item . '</li>';
    }

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

  return $output;
}

```

---
Tags: 7, theming, breadcrumbs
---


# Question
Title: Entity template file/suggestion not working
I've created a entity template file but it's not working. I've looked at the theme registry and I can see the template file is in there but it's not getting applied for some reason.

Thank for you help,

# Answer
I figure this out and it was relatively simple. I added a preprocess function to template.php for entities and added the template file back in to theme\_hook\_suggestions array.

```
function theme_preprocess_entity(&$variables){
  $variables['theme_hook_suggestions'][] = 'entity__your_template_name';
}

```
> 1 votes

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


# Question
Title: Pass no. of pages arguement to Drupal views pager
I have created views with display as page. In pager there is option to set no. of page to show. How can I set this dynamically by passing it through url? I can pass the page using `?page=2` and offset using `?offset=2` but I cant find a way to pass the no. of pages to show.

# Answer
> 1 votes
I still don't quite get what you are asking about, but you should be able to examine `$view->pager` in a hook\_views\_pre\_build and do what you want. For example, this is a snippet of code I have used in Drupal 6 and Views 2 to set the number of items per page:

```
function mymodule_views_pre_build (&$view)
{
    if ($_GET["perpage"]) {
        $perpage = check_plain($_GET["perpage"]);

        if (is_numeric($perpage) && (int) $perpage > 1) {
            $view->pager["items_per_page"] = (int) $perpage;
        } else if ($perpage == "all") {
            $view->pager["use_pager"] = false;
            $view->pager["items_per_page"] = 0;
        }
    }
}

```

---
Tags: 7, views, paging
---


title: Search not selectable on iPhone

text:
# Question
Title: Search not selectable on iPhone
I just finished a mobile-responsive site using an Omega sub-theme in Drupal 7. I just noticed that it is not possible to tap or double tap on an iPhone to access the search field.

I'm not sure where to begin looking for answers to this issue. Any suggestions?

Site:

http://dianalogan.com/

# Answer
> 2 votes
I have found out what was going on. Omega builds the mobile page by changing the side-by-side layout of regions to a stacked layout. The region with the search field and button was layered behind another region in the same zone. Once I removed this layering, there was no issue. An easy fix.

---
Tags: theming
---


# Question
Title: How can I allow authenticated users to edit their nodes only while they are unpublished?
I have a site in which content must be approved by an administrator before it is published. Authenticated users have the ability to submit content, which is unpublished by default. I would also like to be able to have them view and edit content while it is in the unpublished state (for cases in which they realize they made a mistake and would like to correct the submission, etc.)

However, I do not want them to be able to edit the content once it is published, so I don't want to give them blanket edit permissions.

How can I allow them to edit nodes of a given content type only so long as such nodes are in an unpublished state?

# Answer
> 4 votes
You could implement a special hook\_node\_access to return TRUE or FALSE based on the node status.

---
Tags: nodes
---


# Question
Title: Getting started with the Form API and Ajax framework
I'm really struggling to understand how to use Drupal 7's Form API in conjunction with its Ajax framework. I'd like to accomplish the following:

On certain pages, multiple nodes may appear. Each one of these nodes should have a comment form appear right below it. When the user submits a comment, it should be done via Ajax and the resulting comment should then appear under the node in question.

Can someone give me an overview of the steps that are required to do this?

# Answer
There is a module for submitting forms with Ajax.

> Provides AJAX comments to Drupal sites. Features:
>
> * Makes AJAX submits
> * Allows replies to comments on the actual thread page
> * AJAX comments deleting
> * Works with CAPTCHA
> * Cool jQuery sliding
> 4 votes

# Answer
Check out the Examples module. There is loads of information and examples on how to implement AJAX with Drupal 7 forms :-)
> 2 votes

---
Tags: ajax, forms
---


# Question
Title: Search form block not showing in IE7 and IE8
Search shows fine in chrome but not in IE8- looking at the code the DIV block-search-form simply isn't there. This occurs in different themes and also if I change where search should be displayed.

I'm on a fresh install of 7.12 with commerce kickstart, internationalization and other pretty standard modules.

Any ideas?

# Answer
Judging from your commments it's a permission issue. To solve it select People -\> Permissions from the admin menu (or use the path admin/people/permissions) then look for Search and give 'Use search' (and possibly 'Use advanced search') permissions to the roles you want.
> 1 votes

---
Tags: search
---


# Question
Title: How to add an item to the secondary menu in Drupal 7?
So far I've got the two standard menus in Drupal 7: the "main" and the "secondary" links, which are mapped to `Main menu` and `User menu` in the menu settings, respectively.

Now, I'd like to add a simple link to a contact form in the secondary menu, but I can't figure out how. Simply adding a link to `User menu` works fine when I'm logged in, but it doesn't show up for an anonymous user. It seems that the secondary menu doesn't show up at all for anonymous users, even if it is mapped to a custom menu (instead of `User menu`). Is there a way that one can configure the permissions for menus? If possible, I'd still like to have the logged-in menu links (like 'My account' and 'Log out'), as well as having some simple links that are always shown.

Is this possible?

# Answer
> 1 votes
It turns out I was underestimating the system that Drupal uses to display menu items. **Links that go to locations that are unaccessible to the current user are not displayed.** So, for example, if an anonymous user cannot access a certain piece of content, then even the menu link to that content will be hidden.

I was using a contact form to test this with, but the problem was that the site-wide contact form is *hidden* by default. I just had to set the correct permissions, and voilà. Menu item shown.

# Answer
> 3 votes
See www.domain.com/admin/structure/menu/settings

If you set both to "main menu", then the parent items will be in the main menu and child items will be in the second level menu. The menu system will respect the access system, so if a anonymous user does have access to content A. They will not see content A in the menu.

Hope it helps

---
Tags: 7, routes
---


# Question
Title: How to apply header and footer or layout to all pages in a panel enabled website?
I have decided to use the `Panels` module and the `Precision` theme to implement my website. I have designed a front page (using a Panel page) and it has a nice header and footer.

I have also created a user for testing purposes, but when I click on the link in the email to reset the password, I get something like this:

I have some editors (i.e., with a specific user profile) who must be able to create node instances (i.e., tip articles), but without proper layout for standard Drupal pages, the screens are ugly and not functional.

The `Precision` theme does not come with much CSS and layout. How can I implement some minimum layout on all standard Drupal pages and eventually move the header and footer to those pages too? The header and footer are implemented as mini-panels.

I am still new to Drupal. What is the proper strategy here? Thanks.

# Answer
I do not know if Precision has standard regions. IF it has headers and footers, you should be able to access the regions in the admin/structure/blocks page and place your mini panels where you want. If you have chosen Precision because it is minimalist, then you might want to consider adding the 'Panels Everywhere' module. This module works very well with Panels (same authors) and allows you to bypass the Drupal Theming process altogether. This greatly simplified my styling work. Ctools also has a module "Stylizer" which can help defining styles (although it has some limitations in terms of what it can do at the present).
> 1 votes

# Answer
There are lots of answers to your question. Here is mine :)

I usually define 3 areas. The Header and the Footer are "static" blocks that are shown in every site pages. The content is in the middle and is defined with Pages and Panels. That's it!
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Add site details to be used as tokens throughout site
Is there a way to add additional fields to the **config/system/site-information** area such as "business location", "hours of operation", "phone number", etc. I would then like to be able to use that information throughout nodes and blocks as tokens or something like tokens.

That way if a phone number changes or business hours change you can just change it on the config page and it will change throughout the site.

Is this possible?

# Answer
I think you could achieve this by altering the site information form in a custom module to add a custom submit function which would use the Token API to add desired values in tokens.

I found a good post explaining the token part for 6/7 here and a good post for altering the form here.

The module developer's guide is handy too.
> 3 votes

---
Tags: tokens
---


# Question
Title: How to submit a node form with AJAX Drupal 7
How can I set up a node form to submit via ajax. I can't find examples that show how to do this explicitly.

# Answer
Check out this article.

http://drupal.org/node/752056

It should get you started.
> 3 votes

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


title: Update existing nodes via cron

text:
# Question
Title: Update existing nodes via cron
I need to update my nodes created from my own module. The data is extract from my database external.

Now, I want to update this nodes via hook\_cron.. My question is: What is the function that update nodes? Or the steps for do this?

# Answer
I think your looking for node\_save. You can node\_load your node and make changes to the object and then use node\_save to save the changes.
> 3 votes

---
Tags: nodes
---


title: Row templates in Views 3

text:
# Question
Title: Row templates in Views 3
I need to customize the markup for certain fields in my view. In D6/Views 2 This was possible using the templates specified in Views admin under "Theme information," "Row style output." In D7/Views 3, however, these templates in Theme information come up as `.tpl.php, --news.tpl.php, --default.tpl.php, --default.tpl.php, --block.tpl.php, --news--block.tpl.php` and adding those templates does not change anything.

I had found an old issue on drupal.org from a previous version, which had been necro'ed to cover this, but I can't find it now. Is this broken, or am I missing something?

# Answer
> 3 votes
In the leftmost column, Format \> Show needs to be changed from Content to Fields. Hat tip to https://drupal.stackexchange.com/a/5413/4371

# Answer
> 2 votes
You have to be sure where to add the templates depending on your theme, then clear the caches for your templates to be recognized by the system.

Also, the names you indicate should be more precise, with view and display names. If it's not the case, something is broken on your installation.

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


# Question
Title: How to link a Radio Button choice to a taxonomy term or tag
Using drupal 7, when my users select a certain choice out of 2 radio buttons, i want whichever one they choose to also have a tag or taxonomy term applied to it. So if they chose "never" then that node will also have the tag "never"

# Answer
You can achieve that by creating a term reference field for your **content type**(structure \> content types \> your content type \> manage fields) or **users**(configuration \> people \> account settings \> manage fields). Just pick radio/checkboxes widget with only 1 value.
> 1 votes

# Answer
One one you could do this is have the node automatically updated immediately after or before being saved, by using Rules.

You can have a rule set up to check the value of that particular field (with the 2 radio buttons) and depending on the value, or if the field is empty, set up the rule to "Add a value to a list" where the list corresponds to a field on that node enabled for taxonomy terms.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Text format filter for embedding links and videos into body copy
I would like to get a functionality similar to Facebook: when you include any link in a status update, post or comment it will replace it with a thumbnail, link and short description of the page.

The emfield module has that functionality but it requires an extra field and can't do the replacement within a body copy.

Video Filter does it for videos but it requires a special syntax *\[video:url\]* that a user would have to learn. It does offer Wysiwyg integration.

Is there any way of achieving a seamless (Facebook-like) experience?

# Answer
A quick hack in Drupal 6 for the links would be:

```
<?php

function MYMODULE_filter($op, $delta=0, $format=-1, $text='') {
  switch ($op) {
    case 'list':
      return array (0 => t('MYMODULE Open Graph Link Maker'));

    case 'description':
      return t('Changes links into Open Graph Link Blocks with a thumbnail, title, and description');

    case 'no cache':
      return FALSE;

    case 'process':
      return _MYMODULE_og_block($text);

    case 'prepare':
      return $text;
  }
}

function _MYMODULE_og_block($text) {

  $text = preg_replace_callback("`(<p>|<li>|[ \n\r\t\(])(www\.[a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+~#\&=/;-])([.,?!]*?)(?=(</p>|</li>|<br\s*/?>|[ \n\r\t\)]))`i", '_MYMODULE_link_to_og', $text);

  return $text;

}

function _MYMODULE_link_to_og($match) {

  $all = file_get_contents('http://' . $match[2]);      // alas get_meta_tags() only finds tags with name=, not property= like og: uses so we need to do this ourselves...
  $title=_MYMODULE_get_og_meta('title', $all);
  $image=_MYMODULE_get_og_meta('image', $all);
  $description=_MYMODULE_get_og_meta('description', $all);

  if ($title && $image) {
    $content=$match[1];
    $content.='<div style="border:1px solid grey;padding:5px;margin:5px;width:300px;">';
    $content.='<img style="height:50px;width:50px;margin-right:5px;float:left" src="' . $image . '">';
    $content.='<b><a target="_blank" href="http://' . $match[2] . '">' . $title . '</a></b><br>';
    $content.=$description;
    $content.='</div>';
    $content.=$match[3];
    return $content;
  } else {
    _filter_url_trim(NULL,72);                       // these might be different in D7
    return _filter_url_parse_partial_links($match);  // but all it does is the default behavior of changing it into a link
  }

}

function _MYMODULE_get_og_meta($meta, $text) {

  $foo=explode('<meta property="og:' . $meta . '" content="', $text);  // I am sure someone out there can do this better with preg_replace_callback :)
  $bar=explode('"', $foo[1]);
  return $bar[0];

}

```

which looks for www.**\__** and creates a simple facebook like div from the facebook og: meta tags. If you wanted to get fancier, of course you could look for the first image etc in the html in a similar fashion if they weren't present.

Now, I know you said you are using drupal 7, and I think that would be just changing MYMODULE\_filter() to MYMODULE\_filter\_info() and changing up the arrays in the return as the filtering code itself should be the same. Obviously, css style it how you want, I just threw in some quick stuff.

Also, this obviously doesn't do any of the fancy facebook ahah stuff but for something coded while watching Hawaii Five-O, I hope it helps you out a bit :)

Oh, somewhat obviously, to turn it on, you would go into your input filters and add/enable it for filtered\_html, for example, and turn off the original one that changes www.*_*_ into links so you don't refilter it again.
> 5 votes

# Answer
oEmbed project is your friend.

It has many caveats, but oEmbed + Media module will likely get you close, and the issue queue would love you if you help.
> 4 votes

---
Tags: 7, entities
---


title: Using LIKE %...% in Drupal 7, Views 3

text:
# Question
Title: Using LIKE %...% in Drupal 7, Views 3
**I'm trying to change** the Views SQL operator from `= 'String'` to `LIKE 'String%'`.

**I thought the best way to do this was** through `function hook_views_pre_execute(&$view)` at the bottom of `views.module`. I tried that, but any way I edited the query it would throw an error.

For example, I tried str\_replace:

```
function views_views_pre_execute(&$view) {
    if ($view->name == "schools")
    {
        $view->build_info['query'] = str_replace("location.city = :db_condition_placeholder_3","location.city LIKE '".$view->build_info['substititions']['%2']."'",$view->build_info['query']);
    }
}

```

I expected this code to edit the query so it would search `location.city LIKE 'Calgary%'`, but instead I got `Fatal error: Call to a member function addMetaData() on a non-object in [...]/sites/all/modules/views/plugins/views_plugin_query_default.inc on line 1306`.

**I read the documentation**, but it looks like when they refer to Wildcards like %1 and %2, they're referring to arguments passed as contextual filters, as opposed to an SQL LIKE %...% wildcard.

What am I doing wrong?

# Answer
I wound up using the Computed Field module to create a custom SQL query.
> 3 votes

---
Tags: views, database
---


# Question
Title: Is there any way to access the user tables on drupal?
I want to ask where the information about users is saved in the database, since I could not find any corresponding entries in the sql file. I would like to share the user tables with another CMS, namely question2answer.com, so I do not have to maintain two user databases.

# Answer
The users are saved in the database table 'users'.
> 1 votes

---
Tags: users
---


# Question
Title: Site index removes "www" from url and files (e.g., '/about') don't work with "www."
I have a peculiar problem in that people visit any other page other than the homepage with the "www." before the url they will receive an error.

If they visit the index with the "www." it is removed and whatever links they click will work as it doesn't have the "www." in front.

```
http://www.domain.com/        - will change to http://domain.com and work fine
http://www.domain.com/about   - will return '404 Not Found'
http://domain.com/about       - will work fine

```

I have Clean URL's installed (but I can't seem to change any settings in it) and I don't remember touching the .htaccess file.

Any help is much appreciated, thanks.

# Answer
> 2 votes
The following rules remove the www everywhere on your domain. Put it in .htaccess file:

```
  RewriteEngine On
  RewriteBase /
  RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
  RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]

```

---
Tags: uri, .htaccess
---


title: correct primary key indexing

text:
# Question
Title: correct primary key indexing
Perhaps this is more of a DB/SQL question than Drupal. However, when defining large primary keys (multiple cols) how should I be indexing?

In my example below I am both setting a primary key -and- index on multiple cols. This is because I expect to use all of those cols in the WHERE part of queries. Is this correct?

```
  $schema['tournament_stats_node'] = array(
    'description' => 'Stores relations between tournament stats and node.',
    'fields' => array(
      'entity_type' => array(
        'description' => 'Primary key: Entity type of participants, e.g. user/team.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'nid' => array(
        'description' => 'Primary key: Related node ID',
        'type' => 'int',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'default' => 0,
      ),
      'id' => array(
        'description' => 'Primary key: Unique entity ID',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'stat' => array(
        'description' => 'Tournament stat type',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('entity_type', 'nid', 'id'),
    'indexes' => array(
      'entity_type' => array('entity_type'),
      'id' => array('id'),
      'nid' => array('nid'),
      'stat' => array('stat'),
    ),
  );

```

# Answer
> 1 votes
This is not a trivial question and you're actually asking multiple things :)

As mentioned by BetaRide, a technical, auto-generated key has the advantage that it is much simpler to maintain. The primary key defines how the data is stored and if you have a simple key then update/insert/delete should be a bit faster. What's better in general is a hard question to answer, you could make some comparisons (test both approaches, write 1 million rows and then compare update/delete/query speed)

For the indexes, you do most certainly not need a separate key per column. Some hints:

* Only a single index can be used for a single query. Unless you will have queries which only have a condition on e.g. the id, that index is useless.
* Indexes on multiple columns are read from left to right. E.g. a index on A,B,C can also be used for a query with conditions on A and B but not for one on B and C.
* The more indexes you have, the slower are updates.

Same here, I recommend to fill your table with data and then use EXPLAIN to see how your queries are executed and which index they use. Then you can start to optimize things.

# Answer
> 0 votes
There's no reason to put fields in the primary key, just because you want to use a combination of these fields in queries. If the query is slow, use a normal index. Generally primary keys across multiple columns do ask for all sorts of trouble.

---
Tags: 7, database
---


title: Using classes in nodes

text:
# Question
Title: Using classes in nodes
I need a little bit of guidance, I made a custom class and im trying to use it in a node but of course it throwing a white screen at me. So my question is how can I go about using a custom class for d7 so I can include the tag in my node via php.

I put this code in the template.tpl.php file and tried using it in my node but it then gave the white screen.

```
<?php class Colors {

  public function red_form() {
        echo 'color red is here';
  }

    public function blue_form() {
        echo 'color blue is here';
  }

    public function green_form() {
        echo 'color green is here';
  }

    public function purple_form() {
        echo 'color purple is here';
  }

    public function yellow_form() {
        echo 'color yellow is here';
  }
}

$colorforms = new Colors();

?>

```

and im using this in the node.

```
Text here here and here.

<?php $colorforms->red_form(); ?>

More text here here and here.

```

the output im trying to get using the code above is.

```
Text here here and here.

color red is here

More text here here and here

```

is there a module or something for this? or anything to that nature, im a little in the dark on this.

# Answer
Quick fix: declare the class in template.php but instantiate it in your node template (if you check your php error log you probably had something like "Call to a member function red\_form() on a non-object in ..." in it). Also, I am assuming it's a typo that you had $colorforms and $color\_form in your example above.
> 2 votes

# Answer
Don't instantiate classes (or do any business logic) in your `.tpl.php` files: stuff in template files should be in its final, renderable form.

Instead, use a preprocess function in `template.php`:

```
// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_node(&$variables) {
  $variables['colorforms'] = new Color();
}

```

Then, in `node.tpl.php`, reference `$colorforms`1:

```
<?php $colorforms->red_form(); ?>

```

---

As an aside, consider breaking your class into a separate module: doing so would allow you to take advantage of Drupal's autoloader. Create the custom module, place the class in a separate file within the module's directory (let's say, `includes/color.php`).

In the custom module's `.info` file, add the following line:

```
files[] = includes/color.php

```

If you just want to take advantage of the autoloader and don't need any other custom functionality, just use a placeholder `.module` file:

```
<?php

/**
 * @file
 * This file is a placeholder.
 */

```

---

Note 1: Also consider not `echo`ing out information in your class, but returning the string, to allow others to decide how to render the output:

```
public function red_form() {
  return 'color red is here';
}

```

and, assuming you used the solution mentioned here, use this in `node.tpl.php`:

```
<?php print $colorforms->red_form(); ?>

```
> 2 votes

---
Tags: 7
---


# Question
Title: displaying updated time in aggregator block
I'm trying to add a line showing the last updated time for my RSS aggregator feed block (essentially the `checked` timestamp field from the `aggregator_feed` in a formatted manner).

I'm not able to find a preprocess function that lets me get this value.. the closest i got was implementing

```
function mm_theme2_aggregator_block_item($item, $feed = 0) {

  if($item->fid) {
    $fetch_modified_time = "SELECT `checked` FROM {aggregator_feed} WHERE `fid` = %d";
     $feed_last_modified_time = db_result(db_query($fetch_modified_time, $item->fid));
    }
    $last_modified = 'Last Modified time is ' . date('D M d h:i:s T Y', $feed_last_modified_time);
  $output .= '<a class="rssContent" href="'. check_url($item->link) .'" target="_blank">'. check_plain($item->title) ."</a>\n";
  return $output;
}

```

where i'm not sure how to pass on this value to my $block or to $variables. Also this method iterates for each feed item and it'd be unwise to get the same value executed multiple times.

I'm pretty certain there's a drupal based way to get what i desire and am missing something.

Any help/support on this would be really helpful.

Thanks in advance

# Answer
I implemented the above requested functionality by using a template\_preprocess\_block and adding the fetched variable to the $variables\['block'\]. Code for the same as below:

```
    function my_theme_preprocess_block (&$variables) {
      // fetch last updated time for feed 1 only other feeds don't need this value
      if (($variables['block']->module == 'aggregator') && ($variables['block']->delta == 'feed-1')) {
        $last_updated_timestamp = db_result(db_query("SELECT `checked` FROM {aggregator_feed} WHERE `fid` = 1"));
        if (!empty($last_updated_timestamp)) {
          $variables['block']->last_updated_time = 'Last updated on ' . date('D M d g:i:s T Y', $last_updated_timestamp);
        }
      }
}

```

but this seems to look bad as i'm hardcoding my feed id in the query besides the fact that i'm using a query in template.php but it works.

Leaving this question hoping someone could top with a better solution.
> 0 votes

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


# Question
Title: How to modify term reference field in Drupal 7 custom content type?
I am using a term reference field in a content type in Drupal 7 which is a long hierarchical list of categories. In the input form, I want to show them as checkboxes and it gets displayed as a flat list of around 100 items and that of course is not user friendly at all. What hook do I use or where do I manipulate the code of the generated field so that I can display them in a hierarchical way and at the same time use some jQuery to show hide the sub categories. I guess I can intercept it in the theme preprocess and modify the field but I believe theres a better way?

# Answer
> 2 votes
Try the Taxonomy Term Reference Tree Widget.

> This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

Sounds like it would be perfect for your needs, but if not it's fully themable and already has the jQuery functionality built in so would be a very good place to start.

---
Tags: 7, entities, taxonomy-terms, hooks
---


# Question
Title: Can't access template page--node--1.tpl.php by its path
I'm trying to access template page--node--1.tpl.php through /node/1 but seeing 'The requested page "/node/1" could not be found.'

What can I do with this to access this template?

I'm using Drupal 7 and the template is in theme/templates folder.

# Answer
If you're getting a 404 for the path "node/1" then that node doesn't exist, so the template will not be run for it. A template file will only be applied to a path that actually exists.

You just need to get the `nid` of an existing node and replace the id in the template file name with that, e.g.

```
page--node--2.tpl.php

```

where a node with a `nid` of 2 actually exists in the database.

Don't forget to clear Drupal's caches anytime you add/remove a template file so the theme registry gets updated.
> 2 votes

---
Tags: 7, theming
---


title: Static image management module

text:
# Question
Title: Static image management module
I want to display a couple of static images on my Drupal 7 site. I could store them in a specific directory I could create in my theme directory (for example).

However, I was wondering whether there was a module to load such images and let Drupal deal with these. I know it is possible to create image fields, but this is (IMHO) overkill compared to a specific directory solution.

Does such module exist? I can't find any.

# Answer
> 1 votes
If you're just using static images as part of of your theme, you are indeed correct in your suggestion that using an image field is overkill. I'd even go so far as to say it's entirely incorrect to use image fields for static theme content: fields aren't very portable and add way too much overhead to something that'll likely be a part of every page on the site.

Instead, handling static images is built directly into Drupal's core API and theming layer (so, no need for a separate module). What you'll to do is reference the images in your theme using preprocess functions and the Drupal API.

Let's assume you have a logo (`logo.png`) in the `images/` directory of your theme, and you want to display that logo on every page. In the `page.tpl.php` template file of your theme, you could do something like this:

```
<p><img src="/path/to/theme/images/logo.png" alt="My Site" class="logo nav-home" /></p>

```

But that's pretty brittle: what if the theme moves to another directory? What you want to do instead is create a variable such that you could do something like this:

```
<p><?php print $logo; ?></p>

```

To do that, you create a preprocess function to create a variable for use in your templates. In your theme's `template.php` file, create the following function (if it doesn't already exist):

```
// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
}

```

Then, get the path to the logo using `drupal_get_path()`:

```
// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
  $theme_path = drupal_get_path('theme', 'MYTHEME');

  $logo_path = $theme_path . '/images/logo.png';
}

```

Finally, render the path to the logo as an image using `theme_image()`:

```
// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
  $theme_path = drupal_get_path('theme', 'MYTHEME');

  $logo_path = $theme_path . '/images/logo.png';

  // Prepare the information needed to theme an image
  // @see theme_image()
  $image = array(
    'path' => $logo_path,
    'alt' => t('My Site'), // t() makes a string translatable
    'attributes' => array(
      'class' => array('logo', 'nav-home'),
    ),
  );
  $variables['logo'] = theme('image', $image);
}

```

Now, `$logo` is available for use anywhere in your theme's `page.tpl.php`. Do the same process (get the path to the image, then assign the themed image to a variable) for any other static images you want to use as part of your theme.

---
Tags: 7, media
---


# Question
Title: How can I keep the files uploaded by filefield module even though users delete them on node edit form?
On my site users can upload photos by using CCK image field. However I would like to keep the images uploaded by users on the server even though users delete them on node edit form.

I'm not sure if this is possible or not.. Or backing up the images frequently is the only way?

# Answer
I used a module called Filefield Sources together with IMCE. And on the file field's configuration page, I enabled the "IMCE Browser" option for additional sources.

I did a few tests and any files attached to a node using the "IMCE Browser" method doesn't get deleted when the file is removed from a node on node edit screen. But files added through the normal "Upload" method do get deleted, so I think you should upload files using the IMCE Browser too as it has a file uploader as well.

I'm not sure how to remove or hide the actual default "Upload" method on the file field though.
> 1 votes

---
Tags: 6, entities, media, files
---


# Question
Title: Adding javascript to drupal 7 is giving error
i am trying to add code using drupal\_add\_js and separate .js file. Its giving the Jquery is not found error.

```
(function ($) {
 function mobilizeCustomInit() {

                 // Add new Javascript and CSS files to mobile
                 // file loading list

                 // Note: Slashdot at the beginning of the filename
                 // indicates that the file path is relative to the HTML file location.
                 // This is an internal trick of mobilize.js.

               //  mobilize.cdnOptions.javascriptBundles.push("drupal/sites/all/themes/kanji/mobilize.yoursite.js");
               /**
 * This file is executed when the site is loaded in mobile mode.
 */

/**
 * This file is executed when the site is loaded in mobile mode.
 */

mobilize.extend(mobilize, {

    constructBody : function() {
        // Map different elements to jQuery Mobile theme
        this.constructHeader();

        this.constructContent();
        this.constructNavigation();

        this.constructFooter();
    },

    /**
     * Create mobile site header name and buttons
     */
    constructHeader : function() {
        // Map title and header buttons jQuery Mobile

        // This is the mobile target element
        // which will contain the title.
        $('.mobile-header').css('display','TRUE');
        var mobileHeader = $("#mobile-body div[data-role=header]");

        // Pick the current page title from <header> section
        var title = $("header h1").text();

        // Set mobile header title to the same text
        var h1 = $("h1").text(title);
        mobileHeader.append(h1);

    },

    /**
     * Move content area from web site to mobile site
     */
    constructContent : function() {
        var content = $("#content");

        // Place content HTML to mobile content area container
        var mobileContent = $("#mobile-body div[data-role=content]");
        mobileContent.append(content);
    },

    /**
     * Create mobile footer
     */
    constructFooter : function() {
        var footer = $("footer").children();

        // Place content HTML to mobile content area container
        var mobileFooter = $("#mobile-body div[data-role=footer]");
        mobileFooter.append(footer);

    },

    /**
     * Use jQuery Mobile nested list to create a navigation.
     *
     */
    constructNavigation : function() {

        // Get list of items which contain links for the navigation building
        var items = $("#navss li");

        // Create navigation list
        var list = $("<ul class='page-list' data-role='listview' data-inset=true>");

        // Add list header
        list.prepend("<li data-role='list-divider'>Pages</li>");

        // Add list items
        items.each(function () {
            var output = $("<li role='option'>");
            output.append($(this).find("a"));
            output.appendTo(list);
        });

        // Put list below content
        var mobileContent = $("#mobile-body div[data-role=content]");
        mobileContent.append(list);

    }

});
                 mobilize.cdnOptions.cssBundles.push("./mobile-style.css");
            }
})(jQuery);

```

# Answer
I would try to pass the $ alias to your mobilizeCustomInit() function.

Either way, the easiest way to solve your problem would be to just use "jQuery" directly in your code instead of the $ alias if its still giving you problems!
> 1 votes

---
Tags: 7
---


title: Using clientside javascript with Rules

text:
# Question
Title: Using clientside javascript with Rules
I would like to implement a client side javascript action using the Rules module. Has anybody been able to do this?

# Answer
Rules is not designed to work with client side events. They way Rules is designed, it won't make any sense to try to make it aware of client side events.

Your best course of action would be to write some custom JavaScript.

If you want to add some javascript code to a page using rules, that would be possible if you created a custom action that added the JavaSript you wanted to the site.
> 2 votes

---
Tags: javascript, rules
---


title: Image Styles Generate

text:
# Question
Title: Image Styles Generate
I am running a Drupal 7 site that does a call to an external service using Feeds Module, creates nodes from that coming JSON.

The Feeds Module grabs an image, download it, and generate 4 different image styles. Usually in Drupal, you upload the image that goes through Imagecache, and boom the image is re-sized, why because after node\_save you go to node\_view that grabs a function which does the real resizing.

In my case, i do not view the nodes, so the images does not get generated unless i run a whole view/page i created with all images so they get generated.

I tried to curl and request the page on a time interval for the page to get generated but it seems you have to really view the page. What would a solution for this problem be ?

Would doing a batch operation to just view the nodes using node\_view help ? What else ?

*Note that on each Feeds request the site creates around 50 nodes X 4 images = 200 image.*

Help is much appreciated.

# Answer
A derivative image is generated *on the fly* when served over HTTP. When the derivative image is requested in HTTP, if the file doesn't exists, the HTTP request is handled by Drupal. Drupal will use the `image_style_deliver()` page callback to generate the derivative image and deliver it. Once the image exists, Drupal will not handle the request and the file is directly delivered.

If you need to access to files externally without using HTTP to access them, you can use `image_style_create_derivative($style, $source, $destination)` to create the derivatives images. You will need to provide the destination path for the derivative image, which you can get with the `image_style_path($style_name, $uri)` function.

The following (untested) code should ensure that the derivatives for the image file identified by `$fid` are generated for the styles whose names are in the `$styles` array.

```
$original = file_load($fid);
foreach ($styles as $style_name) {
  $derivative_uri = image_style_path($style_name, $original->uri);
  image_style_create_derivative($style_name, $original->uri, $derivative_uri);
}

```
> 10 votes

---
Tags: 7, media
---


# Question
Title: How to generate an unique code for every node
I have a social article website; I created a content type named Article. When a user creates an article, I want to generate a code shown to the user. This code should be saved in the database because users can return to this article with this code. It's important to build a views with this code.

I think I must create a CCK field, generate a code (for example hash the node ID or the timestamp of when the node has been create), and show this code in disable a text box for the author.

Is there any module to do this? What other alternatives do I have?

# Answer
> 3 votes
With some PHP knowledge, you can implemented the field using the Computed Field module. You can also use the module Universally Unique IDentifier. This does not require PHP knowledge, but does not store the code as a CCK field.

---
Tags: 6, entities, hooks
---


# Question
Title: url alias not working in block page restrictions
I've create some blocks that I have set up to show on "Only the listed pages".

I had set up a taxonomy with a url alias and added this alias to the list of pages allowed. This was working few weeks ago. The client has come back saying that the blocks have disappeared from the pages and they have.

When I was looking at the block I took it's none aliased url and put that into the list of allowed urls and then the block reappeared.

Has anyone come across this before and if so was there a reason behind it?

Do I now have to go through the site and put the `node/1` etc.. url into the block allowed lists?

Thanks in advance for your help.

# Answer
> 0 votes
Looks like this has to do with having multiple URL Alias set up for the same page. To fix the issue I had to remove all URL Alias' that were not being used. The blocks then reappeared on the page.

If some else has an answer to this please post and if it fits better than my conclusion I'll mark it as the answer instead of this.

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


# Question
Title: Form API-built form only emails Array, not the form results
I am having a special moment here: I need to send an email with form results. These form results are in two fieldsets. This should be the easiest part of building this, but I'm having a brain freeze. How can I use a foreach loop or something similar to print my form results to the email being sent? Here's what I wrote, which just says 1 instead of the full results array:

```
     $uppgifter = $form_state['values']['dina_uppgifter'];
     foreach($uppgifter as $key=>$value) {
        if ($value > 0) {
            $params['message'][] .= "<p><strong>" . $key . ": </strong>" . $value . "</p> <br />";
        }
    }

```

# Answer
> 1 votes
This line is probably the problem:

```
$params['message'][] .= ...

```

If `$params['message']` is a string then you want to be concatenating directly to that string like this:

```
$params['message'] .= ...

```

When you put empty square brackets `[]` on the end of a variable PHP treats that variable as an array and essentially pushes whatever's after the `=` sign on to the array.

The way you're doing it (with a string concatenation of `.=`) I'm not actually sure what the logic flow would be but it wouldn't be pretty...I'm surprised you don't get a fatal error for this :)

---
Tags: 6, forms, emails
---


# Question
Title: How can I export and import users and their content (preferably as code)?
I've been using the features module successfully to manage configuration changes in content across my dev and production sites.

However, I have a site that is heavily focused on user relationships and I have created a large number of dummy users to test it. I can't use the devel module to do this because I need to create content for each dummy users as well that cannot be random. So, creating this collection of users and nodes has taken a fairly significant amount of time.

I was hoping to find a way to export this set (of users and associated nodes) similar to the way features works, but I haven't been able to find any way to do this. I'd like to export them in order to manage the changes in git as well as to more easily use them across a number of different test sites.

Any ideas on how I can import and export sets of users, preferably as code?

# Answer
You could use backup and migrate to just export the "users" table and if you have additional fields all those "fields" tables.
> 1 votes

---
Tags: users
---


title: Workbench section PHP assignment

text:
# Question
Title: Workbench section PHP assignment
I have problem similar to this one.

I want assign node to section while being created. During php node creation I use:

```
    $node->workbench_access=array('1067');

```

which should assign node to certain section, but after script execution I see "Section: Unassigned".

When I do separately:

```
$node = node_load(823);
$node->workbench_access=array('1067');
node_save($node);

```

..it works. Section gets assigned. As I read Workbench access there might be some bugs preventing this from working (comments like "// Workbench Moderation submits the node twice???" and deleting of redundant nodes?)..

If it was matter of 1 node I would drop it and use second code.. But it seems like I need hundrets of nodes to be created at once so I'd rather avoid loading and saving node only for section assignment.

# Answer
I ended up with my own function that refreshes possible sections. So after I create item in menu - a lot of items - then i just run this, and new sections are available:

```
function update_workbench_sections($menu_name="example1") {

$wanted = array();
$records = db_query("SELECT mlid FROM {menu_links} WHERE menu_name=:menu_name",
                        array( "menu_name"=>$menu_name))->fetchAll();

foreach($records as $w) {
    array_push($wanted, $w->mlid);
}

$access_scheme = db_query("SELECT * FROM {workbench_access}")->fetchAll();
$existing = array();
foreach($access_scheme as $item) {
    if( intval($item->access_id)>0 && $item->access_type_id==$menu_name ) {
        array_push($existing, $item->access_id);
    }
}

$missing = array_diff($wanted, $existing);
$values_to_insert = array();

foreach($missing as $item) {
    array_push($values_to_insert, array( "access_id" => $item, "access_type" => "menu", "access_scheme" => "menu",
                "access_type_id" => $menu_name ));
}

if(count($values_to_insert)>0) {
    $query = db_insert("workbench_access")->fields( array('access_id', 'access_type', 'access_scheme', 'access_type_id'));
    foreach($values_to_insert as $value) {
        $query->values($value);
    }
    $query->execute();
}
workbench_access_reset_tree();
module_invoke_all('workbench_access_save');
return count($values_to_insert);
}

```
> 1 votes

# Answer
Where are you doing the call to workbench? Have you tried doing the call in the postprocess of the node creation. Maybe you don't have the proper database object yet when you do it?
> 1 votes

---
Tags: 7, users, workbench
---


# Question
Title: Artifical part of URL path, not corresponding to node, triggering view attaching
Hello Drupal enthusiasts,

I have a menu structure, which has its equivalent in url paths. Example: department/area/project. This path works fine and now I want to attach some View when last part of url is "releases" (department/area/project/releases).

Any ideas? Should I rather take closer look at Views options or some other module (Pages?) or programatically by hook\_menu and some wildcards?

========================================================= EDIT (thanks to lack of ability of answering my own question): I think I figured out something close to what I need. I create View, type Attachment (thanks to EVA module). I configure contextual filter, and specify validation criteria with PHP code pasted to UI of Views:

```
$path_arr = drupal_get_destination();
$path_str = $path_arr["destination"];
$path_explode = explode("/", $path_str);
$path_last = end($path_explode);

if( $path_last == "releases" ) {
 return true;
}

```

And after that the certain view would be shown in case of last part of path equal to releases. Now some ENTITY CONTENT SETTINGS to cover only selected content type.

If function arg would accept -1 this could be done as fast as

```
if(arg(-1)=="releses") { ... }.

```

How about performance of such a solution? Is it much slowing down the whole thing?

# Answer
> 0 votes
I ended up with using ?subpage in the end of URL. I'm intercepting ?word using:

```
$q = drupal_get_destination();
$q = $q["destination"];
$delimiter = '/\?([a-zA-Z\-]+)=$/';
preg_match($delimiter, $q, $matches);

```

# Answer
> 0 votes
In the *Page settings* section of the view editing form, there is an item labeled *Path*. Click on this item. It allows you to enter the path under which the view will be accessible.

# Answer
> 0 votes
Here are two ideas that might help:

If you expose your view as a block, you can specify in the block settings for it to only appear on nodes of a certain content type.

or

You can specify wildcards in your path settings for a Page view. For instance, you can set a page to display on %/%/%/%/releases.

You can configure arguments that correspond to those % under the arguments section which can affect what appears in your view, or you can add them all as placeholders.

---
Tags: 7, views, hooks, path-aliases
---


title: Securing my drupal website

text:
# Question
Title: Securing my drupal website
I'm working on my very first drupal website and it will consist of a login form which will then give the user access to a form. This next form will allow the user to query my database to show the closest matches in the category they search - and when they select one they will able to fill in some details on another form, attach some files and then send the information via email.

Security is the most important factor here as the information is all confidential. Can you help me work out what plugins/modules I should be looking at to make my system most secure. And what possible security problems I need to be aware of?

\[Note: I have used cmsmatrix.org to compare what the CMS can do and one thing I've noticed is for Drupal it says it can't do things like ssl logins or ssl pages. So should I even be using Drupal in that case?\]

# Answer
I serve several Drupal sites on HTTPS, I don't see what Drupal has to do with that, that's the webservers job to handle. You can test the login for yourself in via HTTPS on drupal.org.

For querying the database in a safe fashion, I would recommend Views. For gathering data with forms, the Webform module. I haven't collected files with Webform, and I'm not sure if that's doable in it's current form. This may require some custom work.

There's a Securing Drupal guide which also specifically mentions getting HTTPS up.
> 6 votes

# Answer
There are several guides available (free or not-free) which might be useful to you:
> 4 votes

---
Tags: security
---


title: How to get commerce billing info fields

text:
# Question
Title: How to get commerce billing info fields
I was wondering how I can get a list of the available checkout fields of Drupal Commerce like: Billing information:

* first name
* last name
* \[custom field\]
* country ...etc.

So i'm only interested in listing the available field names, not the actual values. With code in my custom module.

Does anyone have a suggestion how to do that? Thanks!

# Answer
If I understood you correctly, you want to get a list of the form fields that a user is presented. The isn't really a clean way of doing that, since Drupal forms can be complex. The best solution however would be to generate the form and traverse it. To generate the form, you could do something like this:

```
$form_state = array();
$fields = array();
$profile = commerce_customer_profile_new('billing');
field_attach_form('commerce_customer_profile', $profile, $fields, $form_state);
// $fields is now the customer profile form.

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to place a custom javascript link/button in each row of a Views table
I would like to place a link or button in each row of a Views table, and have custom javascript code executed, with field content taken from that particular row as input. The Javascript code already works fine outside of a Views table. How can I add such a custom Javascript link/button? Is this possible ?

# Answer
If your view is setup to show specific **fields** and not content:

1. Go in advanced \> theming information.
2. Decide after or before which field your javascript should be.
3. Create a template file with the last suggestion name for that field in yourtheme/templates
4. In theming information, click on that field. Copy the whole code. (this is the base code for the template you just created.)
5. Open your template file, write something outside of php tags and save it.
6. Go in configuration \> development \> performance and **clear all caches**.
7. If the text you typed in your template shows in your view page. It worked. Simply paste your javascript instead.

You just learned how to modify views field templates! Hope that helped!
> 1 votes

# Answer
You can use a Global Text field to create the link, and, since Views wraps everything in all sorts of divs, use jQuery to grab any of the other fields there for your js
> 3 votes

---
Tags: views, javascript
---


# Question
Title: Change the way "add content" and "node's" are displayed
I was wondering how one would go about changing the layout of the nodes when you are adding content, as well as when you view the full story.

I want certain text to be bigger, some fields to be placed side by side, some vertically. I want full control over the layout. I tried editing the CSS to change fonts and colors but it all changes fonts for the enitre website and not just in the node view. any thoughts?

# Answer
`page--node--[content-type].tpl.php` = node template for a specific content type (no square brackets)

`page--node--add--[content-type].tpl.php` = node/add template for specific content type.

Copy/paste the code you have in node.tpl.php and **clear your server cache**. Now you can add custom classes everywhere or even create a custom HTML structure to render your fields. See the node.tpl.php documentation and Drupal 7 template suggestions.

Hope this helps!
> 1 votes

---
Tags: nodes, theming
---


# Question
Title: The requested page "/mywebsite/?q=admin%2Fcontent%2Fnode&render=overlay" could not be found
When I am logged as an administrator and try to access `Content` from the administrator menu, the corresponding window pops up, with the `add content` link, but just below, I get the following error message:

```
The requested page "/mywebsite/?q=admin%2Fcontent%2Fnode&render=overlay" could not be found.

```

although content already exists. What is causing this and how can I get rid of it? I am on Drupal 7 release 12. Thanks.

**Update**

If anyone has ideas, tips, suggestions about what is causing (or could cause) this issue, it is welcome. Could I have modified the config by accident (if yes, which)? Is there a tool (other than `FireBug`) to debug this issue? I plan to re-install a system from scratch and check whether the error happens too. Thanks.

**Update II**

Here is what I get when requesting Content from the Administrator menu:

When I click on Amdinistration, I get the following:

First, I notice something strange: an empty entry in the provided list. Why? I don't know.

Second, when I click on `Content` from this page, I am not facing the issue I reported above. I noticed a difference in the URLs between both methods:

```
http://www.mysite.com/#overlay=%3Fq%3Dadmin%252Fcontent%252Fnode <- NOT OK
http://www.mysite.com/#overlay=%3Fq%3Dadmin%252Fcontent <- OK

```

# Answer
> 0 votes
After performing some tests on a new installation, all seems to indicate that my site was installed in a corrupted directory. I had used an installation script delivered by my Internet host, but the install directory was most probably not cleared properly. So my bad on this one.

**Update**

After all, this is a bug I can replicate from a clean system. I opened an issue.

The bug disappears when disabling `Administration views` and clearing cache.

# Answer
> 2 votes
The url you have posted translates to

`admin/content/node?render=overlay`

This is how the overlay works, which displays a regular page, but adds a param to tell drupal it should be rendered as the overlay (no header, footer etc is rendered).

The problem could be that overlay is disabled, or that the url isn't encoded as it should.

If you use clean urls, you shouldn't see the `?q=...`

---
Tags: 7, nodes
---


title: AJAX modify field with multiple values

text:
# Question
Title: AJAX modify field with multiple values
I'm trying to use ajax to update the value of a field that can have unlimited values. I am using hook\_form\_FORM\_ID\_alter() to add a button to the form with an ajax callback. The problem is that I can not simply set `$form['field_name']['language'][0]['value']` because I need to add/remove items from the fields value. So what I've done is change the value on the entity in `$form_state` and build the form again. The field reloads with the items that I set but when I save the entity only the first new item saves. For example, if the field has no value then only one of the items will save; if the field has one item already then the first two items will be saved; etc.

In my specific example I am using the commerce\_product form with a commerce\_installments field. However, I have created a simplified example using nodes. I have created a content type called testing with an integer field called field\_int\_test that has a cardinality of -1 (unlimited). The "Calculate" button I have added to the form uses ajax to generate a random number of items from 2-10 for the field and sets each item's value to a random number. Clicking "Calculate" reloads the field with the new items, but saving exhibits the same behavior as above. I have checked the post and all of the values are being posted back to the web server so I am not sure where the problem is. Also, I feel that there has to be a better way to do this but I have not come up with one.

I have included the code used for the simple node example below. Any help is greatly appreciated.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_testing_node_form_alter(&$form, &$form_state, $form_id) {
  $form['calculate'] = array(
    '#type' => 'button',
    '#value' => t('Calculate'),
    '#ajax' => array(
      'callback' => 'mymodule_testing_ajax',
      'event' => 'click',
      'wrapper' => 'testing-replace',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#weight' => 1,
  );

  $form['field_int_test']['#prefix'] = '<div id="testing-replace">';
  $form['field_int_test']['#suffix'] = '</div>';
}

/**
 * AJAX callback that will generate a random number of items for the
 * field_int_test field wiht random values for each and re-build the form with
 * the new values.
 */
function mymodule_testing_ajax(&$form, &$form_state) {
  $total = mt_rand(2, 10);
  for ($i = 0; $i < $total; ++$i) {
    $form_state['node']->field_int_test['und'][$i]['value'] = mt_rand();
  }

  $form_state = array(
    'build_info' => array(
      'args' => array($form_state['node']),
    ),
    'node' => $form_state['node'],
    'cache' => FALSE,
    'no_cache' => TRUE,
    'input' => array(),
  );
  $form = drupal_build_form('testing_node_form', $form_state);

  return $form['field_int_test'];
}

```

I have made some changes to the callback function (see below) that now allows the field to be saved but any changes made to the node form after clicking "Calculate" will not be saved; this includes changes to the field being calculated. I have modified the callback to save the new form and form state into new variables, replace `$form['field_int_test']` with the value in the new form and update the form's cache.

```
/**
 * AJAX callback that will generate a random number of items for the
 * field_int_test field wiht random values for each and re-build the form with
 * the new values.
 */
function mymodule_testing_ajax(&$form, &$form_state) {
  $total = mt_rand(2, 10);
  for ($i = 0; $i < $total; ++$i) {
    $form_state['node']->field_int_test['und'][$i]['value'] = mt_rand();
  }

  $field_form_state = array(
    'build_info' => array(
      'args' => array($form_state['node']),
    ),
    'node' => $form_state['node'],
    'cache' => FALSE,
    'no_cache' => TRUE,
    'input' => array(),
  );
  $field_form = drupal_build_form('testing_node_form', $field_form_state);

  $form['field_int_test'] = $field_form['field_int_test'];
  form_set_cache($form['#build_id'], $form, $form_state);

  return $form['field_int_test'];
}

```

# Answer
> 4 votes
I found that my problem was both how I was rebuilding the form and when. Instead of doing a full build I needed to call `drupal_default_form()` to build just the field's form and I had to do it during `mymodule_form_testing_node_form_alter()` rather than the ajax callback. My completed code is below:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_testing_node_form_alter(&$form, &$form_state, $form_id) {
  // If this form has been submitted by "Caluculate" button then we need to
  // process the form to calculate and add the integers based on the user's
  // input.
  if (isset($form_state['triggering_element'])
    && $form_state['triggering_element']['#value'] == 'Calculate') {
    _mymodule_calculate_process_form($form, $form_state);
  }

  $form['calculate'] = array(
    '#type' => 'button',
    '#value' => t('Calculate'),
    '#ajax' => array(
      'callback' => 'mymodule_testing_ajax',
      'event' => 'click',
      'wrapper' => 'testing-replace',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#weight' => 1,
  );

  $form['field_int_test']['#prefix'] = '<div id="testing-replace">';
  $form['field_int_test']['#suffix'] = '</div>';
}

/**
 * AJAX callback to reload the integer test field with calculated values.
 */
function mymodule_testing_ajax(&$form, &$form_state) {
  return $form['field_int_test'];
}

/**
 * Process a form submitted via AJAX to calculate the value of the integer test
 * field.
 */
function _mymodule_calculate_process_form(&$form, &$form_state) {
  // We don't care about the installment field values that were submitted with
  // the POST.
  unset($form_state['values']['field_int_test']);
  unset($form_state['input']['field_int_test']);

  $items = array();
  $total = mt_rand(2, 10);
  for ($i = 0; $i < $total; ++$i) {
    $items[$i]['value'] = mt_rand();
    $form_state['node']->field_int_test['und'][$i]['value'] = $items[$i];
  }

  // Update the items count for the field.
  $form_state['field']['field_int_test']['und']['items_count'] = count($items);

  // Build the field form with the new values.
  $language = $form['language']['#value'];
  $field = $form_state['field']['field_int_test'][$language]['field'];
  $instance = $form_state['field']['field_int_test'][$language]['instance'];
  $field_form = field_default_form('node', $form_state['node'], $field,
    $instance, $language, $items, $form, $form_state);

  // Replace the field form that was built previously with the new one.
  dpm($field_form['field_int_test']);
  $form['field_int_test'] = $field_form['field_int_test'];
}

```

I will refrain from accepting my own answer for the time being, in case somebody else has a better solution.

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


title: Views sort for right to left language

text:
# Question
Title: Views sort for right to left language
The titles of my nodes in Drupal 7 contain Urdu langugage (RTL) content. I have created a glossary view using Views module.

The alphabets of Urdu language are not in right order as they are in the original language.

For example, (س (1) | ش (1) | ص (1) | ض (1) | ٹ (1) | پ (2) | چ (1) | ڈ (1

How do I fix sorting for View?

# Answer
You don't. At least not in Views. That's not the task of the client, that's the task of the server. Set a proper collation for the column and / or table. If you really wanted to, you can write a sort handler to use `ORDER BY collation` but changing the collation with `ALTER TABLE` is the right thing to do.
> 3 votes

---
Tags: views, i18n-l10n
---


# Question
Title: Add scrolling effect to hidden node title
Here: http://jsfiddle.net/sdleihssirhc/AYYQe/3/

There is a nice JavaScript code to ellipsize text when it’s too long. On hover, the text slide to the left, and show the hidden part. I’m struggling to make this script work in a view, to ellipsize and show hidden part from node titles. This is my View structure.

```
<div id="view">
<div class="thumb">[picture]<span class="thumb-overlay"></span></div>
<h2 id="tweet">[title]</h2>
</div></div>

```

this is the CSS I’m using:

```
#tweet, #tweet_js { border:1px solid red; width:25em; padding:.5em; }
#tweet_js { overflow:hidden; white-space:nowrap; }
.hiding { text-overflow:ellipsis; }

```

and this is the code:

```
var tweet = document.getElementById('tweet');
tweet.id = 'tweet_js';
tweet.className = 'hiding';

var slide_timer,
max = tweet.scrollWidth,
slide = function () {
    tweet.scrollLeft += 1;
    if (tweet.scrollLeft < max) {
        slide_timer = setTimeout(slide, 40);
    }
    };

tweet.onmouseover = tweet.onmouseout = function (e) {
e = e || window.event;
e = e.type === 'mouseover';
clearTimeout(slide_timer);
tweet.className = e ? '' : 'hiding';
if (e) {
    slide();
} else {
    tweet.scrollLeft = 0;
}
};

```

I added the JavaScript file in in the module's .info file using this :

```
scripts[] = script.js

```

but nothing is working, I have tested this JavaScript code in HTML page, and its working only when placed before the ending body tag.

---

(JavaScript and CSS are not mine, they were posted by sdleihssirhc as an answer to this question: https://stackoverflow.com/questions/4755593/css-jquery-powered-sideways-scrolling-text-on-hover )

# Answer
There should be no direct errors if you got it working on a HTML page. I would suggest checking from the html source that your js file is actually loaded (if not clear the caches). Additionally try wrapping the javascript code inside

```
jQuery(document).ready(function() {
  //code here
});

```

or a possibly better option with Drupal 7:

```
Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // code here
  }
};

```

You might find additonal useful info about managing javaScript in Drupal 7 here.
> 1 votes

---
Tags: views, javascript
---


# Question
Title: Why doesn't variable_set() work in an installation profile?
I'm writing an installation profile, and I want to display some forms on some pages. The form below intended to set a variable at submission time. It does not work in the profile, but it works on an installed site. Why? Where is mistake?

```
function myprofile_install_mode_form() {
  $form = array();
  $form['myprofile_install_mode'] = array(
    '#type' => 'radios',
    '#title' => st('Please select'),
    '#default_value' => 0,
    '#description' => '',
    '#options' => array(st('Option 1'), st('Option 2')),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => st('Continue'),
  );
  return $form;
}
// Submit handler
function myprofile_install_mode_form_submit(&$form, &$form_state) {
  $value = $form_state['values']['myprofile_install_mode'];
  variable_set('myprofile_install_mode', $value);
}

```

# Answer
> 2 votes
`variable_set()` works fine in installation profiles (`standard_install()` uses it), it's more likely that the submit handler for your form isn't being run. I seem to remember having to explicitly set the submit handler for one of these extra installation forms:

```
$form['#submit'][] = 'myprofile_install_mode_form_submit';

```

Try adding a call to `drupal_set_message()` in the form submit handler to make sure your code is definitely being run.

---
Tags: 7, configuration, distributions
---


# Question
Title: How can I implement OAuth based login, just like drupal.stackexchange.com offers?
> **Possible Duplicate:**
> What are the differences between the various OpenID widgets available?

I know there is the Janrain Engage module, but I don't want to depend on an external provider. Can I implement it with any Drupal module?

# Answer
Stack Exchange uses OpenID for single-sign-on, which is not the same as OAuth. The good news is, OpenID is built-in to Drupal core. The downside of using the core module is your visitors must know the URL of their OpenID provider. Most people already have at least one OpenID provider, but don't know it.

To solve this problem, you could try OpenID selector, which offers a login selector similar to SE.
> 3 votes

---
Tags: users, authentication-authorization
---


# Question
Title: Uploading videos with the Media uploader
I am trying to create a video gallery. I was originally trying to use the Media module with shadowbox to display them, but I have not been able to figure out how to get a thumbnail for the media. What I came up with was the Video module. The video module allows me to create a thumbnail, however I wanted an uploader similar to the media module one, which allows me to upload it, get it from the web, or use a video that is already in my library. Is there an ad-on module for Video that will allow me to upload videos like this?

# Answer
The video module is strictly for videos that your users upload. You need to configure the transcoding (ffmpeg on your server or use the external Zencoder service). If you want to embed Youtube or Vimeo videos you can use video embed field module.

I've combined the two to allow video uploads and video embeds. However I really prefer the video embed field since dealing your users uploading a ton of large video files isn't trivial.
> 1 votes

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


title: indexing nodes and links in views

text:
# Question
Title: indexing nodes and links in views
I have a content type that contains text, picture and term reference (cat, dog). I've used views and create a page with cats and a page with dogs.

The problems:

1. I want only 2 pages indexed by Google. The dogs page and the cats page. I don't want Google to index my nodes separately. Now I have one page with all my cats, one with all my dogs ( \<\< the pages that should be indexed by Google and published for the users) and one page for each cat and one for each dog ( \<\< pages that i don't want).
2. On my front page I need a 2 column area : column1, column2. Both columns should contain text and image. ( If I create new content type and then use a view I have the same problem as above.) When I click column1 I want to go to cats page. When I click column2 I want to go to dogs page. How can I assign links different links for the view results? I know I have "Output this field as a link" in "REWRITE RESULTS" but it uses the same link for all views elements. I also know about "Link this field to the original piece of content". But this mean that my info from column1 should be in cats page and from column2 in dogs page. And I only wish to display the info from column1 and column2 on my front page.

How could I solve this ? Which is the best solution in order to create something like this ?

# Answer
> 0 votes
1. Use http://drupal.org/project/node\_noindex for noindexing concrete nodes.
Or modify robots.txt for excluding count of nodes, `Disallow: /node/`, for example, next help for you: Robots.txt Tutorial.
2. Do you mean that clicking on whole column should lead to cats/dogs? If so, create custom template (in Views editing you should see in "Theme:Information" -\> "Display output" -\> take latest filename and copy source from link. Create this with filename and paste source. Wrap whole code into ....

---
Tags: views, nodes, navigation
---


# Question
Title: Popups API - Drupal 6.x-2.0-beta0 - Popup is automatically closing
I am trying to add the site contact form in popup using Popups API - Drupal 6.x-2.0-beta0 module. In popups\_test.module popups/test page I am able to add the link contact like following

```
function _popups_test_popups() {
  popups_add_popups();
 $output .= '<li>'. l("Contact Us", 'contact',
               array( 'attributes' => array('id' => 'test-popup','class'=>'popups')));
return $output;
}

```

Everything is working fine.

The same thing I am trying to add in a block like following

```
<?php
popups_add_popups();
print l("Contact Us.", 'contact', array('attributes'=>array('class' => 'popups')));
?>

```

Using this the popup is opeing and facing following issue, 1. when I submit the contact form without enter any information the popup is disappearing. Anyone came across the same issue? Any help will be appreciatable

# Answer
> 1 votes
I have did some analysys and changed the following code its started working

```
$settings['popups']['originalPath'] = $_GET['q'];

//Replaced with following code

$settings['popups']['originalPath'] = 'popups/test';

```

There is a function in popups.js which will check the end point of the form. Not sure exactly the cause of the issue.

```
 return done = (path === Popups.originalSettings.popups.originalPath);

```

---
Tags: blocks
---


# Question
Title: Manually including Webform in a single node
Anyone know how to include Webform module into a single node? Is there a function I can include to do this.

# Answer
> 2 votes
A discussion on Drupal has resulted in a patch that allows you to display a webform in a block (and then you can display that block only on your node tpl page).

EDIT: The patch has been included in the latest version of webform.

Additionally, you could try using this PHP code:

```
<?php
    $node = node_load($nid);
    print node_view($node);
?>

```

---
Tags: 7, webforms
---


# Question
Title: Order Total not updating after I change the line item price
I have a custom form which on submit creates a new order, loads a product and a custom line item type. I then save the information from the form in the line item. The line item price is updated via a rule which calls a custom PHP function. The problem is when I redirect to checkout/order\_id the **Order Total** is not updated.

I've tried altering the order directly using my order\_wrapper and i've also tried using commerce\_price\_component\_add. I tried a rule which called "Save entity" again but nothing seems to be working.

Can somebody give me a point in the right direction on how to get the order total to re-calculate.

Also if anyone has any good examples of creating orders using custom line item types from a custom form that may be helpful

# Answer
> 4 votes
The solution was to use `commerce_price_add_component()`

```
    $line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $commerce_line_item);
    $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
        $line_item_wrapper->commerce_unit_price->value(),
        'base_price',
        array(
                'amount' => $booking_price,
                'currency_code' => 'AUD',
                'data' => array(),
        ),
        TRUE
);
}

```

---
Tags: commerce
---