# Question
Title: Checking if user is logged in and inputting their username
I have a form on my website and i would like the page to check if the user is logged in, if they aren't, then redirect them to a login page, if they are, then show the form.

When they are submitting the form, how can I get that users username and get that review that they submitted show up on their account?

If you need any more details just comment.

I am using Drupal 7

# Answer
> 1 votes
1. First make sure only users with a specific role can access this form. You can use the `#access` property to restrict the access to a specific form.
2. The LoginToboggan module can redirect the user to the login page if they get an access denied.
3. In the submit hanlder of your form you can access the current user by adding `global $user` at the top of your method.

# Answer
> 1 votes
Assuming 6.
You can use global variable `$user` to check if the user is anonymous or authenticated. If authenticated the same variable will also hold username and loads of other information.

In `foo_bar_form()`

```
global $user;
if($user->uid == 0){
// Anonymous user redirect to login page
}

```

In `foo_bar_form_submit()`

```
global $user;
// To get user name
$user_name = $user->name;

```

You need to create a flag(profile\_value perhaps) and update this when a user submits. So that next user logs into the application you need to check for this flag if set or not and proceed accordingly.

# Answer
> 0 votes
I think we need several more details. When you say "the review that they submitted," what kind of entity are you talking about? Is a review a node? A comment? Something to do with a custom module like fivestar?

Whatever it is, BetaRide is right about LoginToboggan; if you can restrict the creation of these reviews to authenticated users, then you can use LT to redirect them to log in if they attempt to create one as an anonymous user.

As for "showing up on their account," that also requires more details, but once you've made the user the author of whatever entity is serving as your review, chances are you can use a view to generate a list of reviews created by a particular user and display that on the user's profile page.

---
Tags: forms, users
---


# Question
Title: How to manipulate field with Number of value "unlimited" through php
I've got a field image with unlimited number of value and a view who shows 12 of them from different node(in this case I can not use delta). Now instead of showing the 8th and the 11th pictures I want to show a blank box with text.

I would like to insert this loop so I installed view PHP and I wrote this code on the box "Output code"

```
$counter = 0;
foreach ($row->field_image as $image){
  if ($counter++ = 8){
  echo "something";
continue;
}
  if ($counter++ = 11){
  echo "something else";
continue;
}
print $images;
}

```

What am i doing wrong? How can I get the result I want? Thanks in advance

# Answer
> 0 votes
I've found the solution. I was trying to output 12 images from different contents. Each contents has got more than one image using one image field with number of value "unlimited". I was trying using View PHP module and adding something like this

```
$counter = 0;
foreach ($row->field_image as $image){
  if ($counter++ == 8){
  echo "something";
continue;
}
  if ($counter++ == 11){
  echo "something else";
continue;
}
print $images;
}

```

But I was getting just numbers 1 and 2 (probably the node id, I've got just two nodes for the moment.)

I start to go around the web with no result so I've started to play around with fields and the view theme (views-view-unformatted--portfolio--page-2.tpl.php). I found one problem there, each group of images of one node was in one row but I should have one image per row, does not matter if they were from the same content (I've got random sort criteria). So I went into the view, I clicked on the image field and under "Multiple field settings" I dunchecked "Display all values in the same row " so I could get them in different rows. I edited the views-view-unformatted--portfolio--page-2.tpl.php in this way

```
<?php
$counter = 0;
 foreach ($rows as $id => $row) {
 $counter++;
 print '<div class="'.$classes_array[$id].'">';
 if ($counter == 8) {
   print 'Something';
 } elseif ($counter == 11) {
   print 'Something else';
 } else {
  print $row;
  }
  print '</div>';
  }
  ?>

```

Here we go. I've got the thing I wanted without using the View PHP. Thanks to David Meister for suggesting me to put the $counter++ outside the if statement, it works much much better.

# Answer
> 1 votes
Those if($counter++ = 8) lines look whacky to me.

don't you mean:

```
$counter++;
if( $counter == 8 ) {
  /* do stuff */
}

```

checking for equality is == or === not =

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


title: Custom display for text field

text:
# Question
Title: Custom display for text field
I am new at Drupal, so I apologize if I am missing something obvious.

I have a content type that has some fields. This field is text and I want to have a custom "Field Display" for it.

I can do the JavaScript JQuery stuff to have a div expandable with a click, etc, but I don't know how to make that happen.

How do I change the field display for a field so that I can customize its look (with css or some elements or javascript). I don't want to put this stuff in the content of the field, as I don't want the content author to have to put that in every time.

Thanks.

# Answer
1. You can find the CSS class or id by installing firebug in your Firefox installation. It let's you point and click on every area of the page.
2. If this is not enoug install the Theme Developer module (http://drupal.org/project/devel\_themer). It helps you to find the appropriate theme merhods and template files to tweak the output to your needs.

If this is all strange stuff, make yourself familiar with basics about drupal theming. This is a good starting point: http://drupal.org/documentation/theme
> 1 votes

---
Tags: entities, javascript
---


title: Unable to add JavaScript on a page

text:
# Question
Title: Unable to add JavaScript on a page
I am using this, but I don't understand why it's not working.

```
if ($_SERVER['REQUEST_URI'] == '/node/1') {
  drupal_add_js(drupal_get_path('theme', 'sanskrit').'/sites/all/themes/sanskrit/scripts/jquery-1.4.3.min.js', 'inline');
  drupal_add_js('/sites/all/themes/sanskrit/scripts/scripts/jquery.nivo.slider.pack.js');
}

```

What I want to do is adding specific JavaScript files when the user is viewing the front page.

# Answer
> 17 votes
This should do it:

```
function MYTHEME_preprocess_page(&$vars) {
  if (drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/MYSCRIPTS/myscript.js');
    $vars['scripts'] = drupal_get_js();
  }
}

```

FYI: You'd use `drupal_get_js` in case any modules are also using `hook_preprocess_page` and setting new scripts themselves.

Also, I wouldn't just add a newer version of jQuery in willy nilly. Try either jQuery Update or jQuery Multi

# Answer
> 4 votes
Alternately: The JavaScript Libraries module. It doesn't let you limit the script to the front page, but is certainly much easier than writing a module just to load a script.

# Answer
> 3 votes
If you are working with a module, you put it in hook\_init like this:

```
function mymodule_init() {
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'sanskrit') . '/sites/all/themes/sanskrit/scripts/jquery-1.4.3.min.js');
    drupal_add_js(drupal_get_path('theme', 'sanskrit') . '/sites/all/themes/sanskrit/scripts/scripts/jquery.nivo.slider.pack.js');
  }
}

```

If you want to put it in preprocess\_page:

```
function yourTheme_preprocess_page(&$vars) {
  if(drupal_is_front_page()) {
     drupal_add_js(drupal_get_path('theme', 'sanskrit') . '/sites/all/themes/sanskrit/scripts/jquery-1.4.3.min.js');
     drupal_add_js(drupal_get_path('theme', 'sanskrit') . '/sites/all/themes/sanskrit/scripts/scripts/jquery.nivo.slider.pack.js');
     $vars['scripts'] = drupal_get_js();
  }
}

```

Or you can put it in your theme.info file if you are building your own theme.

```
scripts[] = scripts/jquery.nivo.slider.pack.js

```

# Answer
> 2 votes
The best and simplest means to accomplish adding javascript to a front page is via context and context add assets. Context and context add assets are exportable as well and you can create a feature to be used later on.

More about context add assets:

> This module will add a reaction within context to add theme, module, or custom folder files to your page(s).
>
> Ever wanted to quickly add a css file to a theme? Include a js file on only one page (or section?)
>
> Make using multiple CSS files a breeze with this module and harness the power of Context in your theme!

# Answer
> 1 votes
It is not working because you are concatenating the string returned from `drupal_get_path('theme', 'sanskrit')` with `'/sites/all/themes/sanskrit/scripts/jquery-1.4.3.min.js'`; supposing that you didn't install Drupal in a sub-directory of the server root directory, the filename you are passing to `drupal_add_js()` is sites/all/themes/sanskrit/bbbsites/all/themes/sanskrit/scripts/jquery-1.4.3.min.js.

The code you should use is the following one.

```
if ($_SERVER['REQUEST_URI'] == '/node/1') {
  $theme_path = drupal_get_path('theme', 'sanskrit');
  drupal_add_js($theme_path . '/scripts/jquery-1.4.3.min.js', 'inline');
  drupal_add_js($theme_path . '/scripts/jquery.nivo.slider.pack.js');
}

```

As others pointed out, to check if the user is viewing the front page, you just call drupal\_is\_front\_page().

Paths like sites/all/themes should be never hard coded in a theme/module code, as a theme could be installed in `sites/<domain.name>/themes/<theme.name>`, and a module could be installed in `sites/<domain.name>/modules/<module.name>`. Suppose that the Drupal installation is used for the domain blog.example.com, the Views module could be installed in sites/blog.example.com/modules/views, and a theme like the Whitebull theme could be installed in sites/blog.example.com/themes/whitebull.

---
Tags: javascript
---


# Question
Title: What does it mean if an item in Search API has a "-1" flag and is never indexed?
Search API uses flags in the `changed` column of the `search_api_item` table to store item-level information relating to indexing. The -1 flag (something to do with queuing items?) appears to be crucial to a problem I'm facing, where it is set on items which are then never indexed.

I've studied the code and all the documentation and relevant issues I can find, and I can't figure out in nearly enough detail what the practical implications of this flag are: what it being set causes or prevent from happening (and therefore, where I should focus next in trying to solve my problem). Since Search API is an API module which plenty of developers work with, and these flags are a core part of its logic and an important part of the contrib-accessible data it records, I'm hoping that someone will be able to help explain what a -1 flag means and what it causes to happen (or what it prevents).

For context, the specific problem spurring me to ask (with Search API using Search API Solr on Drupal 7) is that indexing stops abruptly - cron runs continue to work fine, cron requests reach the search server with no problem, but a large portion of my indexable items are never indexed. There are no error messages or relavant information in any of the appropriate logs (drupal watchdog, cron, apache solr, tomcat). It's a classic debugging nightmare: something is failing silently and leaving no trace. But there's one clue: in the `search_api_item` table on the database, I can see that, when Cron reaches those items where indexing is failing, the `changed` column changes to a '-1'. The notes for that column say:

> Either a flag or a timestamp to indicate if or when the item was changed since it was last indexed.

After much digging in code I found what appears to be the place these flags are set ( in `search_api/includes/datasource.inc` ) and there appear to be three such flags:

* -1, set in `trackItemQueued()`: the one which looks to be crucial to my problem. According to the comments it means "queued" - but I can't find the crucial details of what this causes to happen (or prevents from happening) next. If I've understood this right, then this flag being set should be a sign that everything is working fine: but the items aren't indexed, and I can't see what the expected next step should be.
* 0, which apparently means already indexed (presumably causing these items to be passed over)
* 1, set in `trackItemInsert()`, and I can't figure out anything about what this one means
* (and timestamps apparently signify "changed/dirty", which I imagine means "no longer matches the index data as of \[timestamp\], needs to be queued for re-indexing")

Search API is an API module, so there will be a good number of Drupal developers who know how it works on the inside. Do you know what the -1 flag indicates - in terms of what then happens to items flagged ("queued", or, "marked to be queued") in this way? What is the role of this flag in the process and what happens next?

---

(bonus points for any expert advice on the next step to take in debugging a problem like mine: but the focus of my question is general, about understanding the Search API item flags. My issue and attempts at debugging it are intended mainly as context. In case it's relevant further context, I'm also running Ultimate Cron and its dependency Background Process to handle the cron runs, to reduce search server strain by allowing lots of small indexing batches called by cron every few minutes without overdoing other drupal cron functions. This part of the process seems to work fine: the search server is reached perfectly in sync with the Ultimate Cron schedule as expected. It's what happens after the item flags are checked and updated that is leaving me stumped)

---

(I've also posted a related support request on the Search API issue queue, without a response. I'm judging it's okay to ask here as well because a) this meta discussion explicitly says that also posting questions that are *support questions* also asked in issue queues here as well is okay and also a desirable way to take the pressure off busy module maintainers, and b) this is particularly true for Search API as the maintainer has said in the past that he doesn't have much time available to help with support issues. As adivsed on Meta, I'll update both threads with any relevant information)

# Answer
> 2 votes
-1 means that it's added to the queue system. By default, that means the queue table in the database. It should create a queue task for groups of id's matching your batch size.

If they aren't run, this either means that the queue system does not run at all (It should be executed in the default cron implementation) or that some other stuff is filling up the queue. The following query should give you an idea of what's in the queue: `SELECT name, COUNT(*) FROM queue GROUP BY name`.

Some hints:

* There was a quite major bug in the update.module that caused it to create possibly thousands of duplicate queue tasks. If you can see many fetch\_tasks with the above query, you can delete them and clean the cache\_update table to have them re-added once. Make sure you're running an up to date Drupal core version to prevent this from re-appearing.
* Maybe one of your cron implementations is running into a timeout or fatal error. You could try a module like Elysia cron to get detailed stats about how much time each cron implementation uses. It probably is something that is run after search\_api.module because it seems to be able to create the queue tasks. xmlsitemap.module is a candidate that can take a huge amount of time if you have many nodes.
* You're using an alternative cron module, that is not properly executing queue tasks.

You can also try http://drupal.org/project/queue\_ui, it provides an UI to manage the default queue implementation and provides the same information as the above query, but it's not actively maintained and broken without applying a patch from the issue queue.

---
Tags: cron, search, queue
---


# Question
Title: Not able to navigate through different sections of administrator page of fresh installed drupal 7.14
At the first instance after finishing installation the link "Go to your new website" directs to the parent directory. Then I tried with appending "index.php" to "http://localhost/drupal/" it displayed admin home but now Clicking on any link displays the root directory of drupal site. I am not able to navigate through different sections of administrator page of drupal.

# Answer
> 1 votes
During drupal installation you should be careful of following things;

1. Download and unzip drupal properly.
2. copy and paste that into your var/www (for linux) and xampp/htdocs (windows).
3. Rename the drupal folder to ur project name. Don't make any subfolder.
4. Make sure there is no spaces during renaming the drupal folder.
5. After creating database. Doing changes in settings.php run install.php in ur browser.
6. If u r using linux give all permissions.

---
Tags: installation
---


title: Multi user registration

text:
# Question
Title: Multi user registration
As per the requirement, we need to have two separate registration forms student and companies with different kind of fields.

We planned to use current drupal registration as student registration form with multiple custom fields. (And the values will store in the users table of DB)

Now please provide us a kick-off for creating custom company reg. form which have different fields compare with the student reg. form and store the values in separate table in the DB.

Kindly suggest us.

# Answer
> 1 votes
I'll use default registration for students. Submit of second form will add different role (and register too).

Check this module too: http://drupal.org/project/user\_role\_field/

# Answer
> 0 votes
You can do this using Profile 2 module. And also use roles and permission.

---
Tags: users, forms
---


# Question
Title: How to add a flat amount to an order. Using Drupal commerce module
I need to add a flat amount to an order using the http://drupal.org/project/commerce module.

Lets say I have a order with 3 products then I need to add an amount of 230€ to the total order cost. This amount is a flat amount (it will ever be 230€), it doesn't care how many products there are in the order.

I would use a Sales Taxes type tax but since it only accept percentages it is not useful for me.

# Answer
> 3 votes
You should be able to accomplish that using Rules.

Create a product that has the flat amount of 230€ and use the Rules action "Add product to the cart" to add that product to the cart.

To create the rule:

1. Create a Rule for event "After adding a product to the cart"
2. Add the "Order contains a particular product" condition to check if the order already has the flat amount product
3. Then add the "Add a product to a cart" to add the flat amount product to the order

You could add the same rule for the "After removing a product from the cart" event, so if they remove the flat rate product, it would just re-add it to the cart.

# Answer
> 0 votes
You can achieve this using pricing rule in drupal commerce. Go to the admin/commerce/config/product-pricing, then create new pricing rule. You can add event as per your requirement.Also you can add actions and conditions for your products.

---
Tags: commerce
---


# Question
Title: Fatal error: Call to a member function advanced_render() on a non-object
What I am doing wrong? The error says:

> Fatal error: Call to a member function advanced\_render() on a non-object in /var/www/mydrupalsite/themes/myTheme/template.php on line XXXX

```
/**
 * Overrides theme_views_view_field for a view
 *
 */
function myTheme_views_view_field($view, $field, $row) {
  //Work only for mobile view and section field
  if($view->name == 'mobile' && $field->options['label'] == 'Section') {
    $new_items = array();

    foreach($field->items as $skey => $subitem) {
      $new_items[$skey] = array();

      foreach($subitem as $key => $item) {
        $parent = taxonomy_get_parents($key);
        if(count($parent) == 0){
      //do not set item in items, if taxonomy does not have parent
        }
       else {
         $new_items[$skey][$key] = $item;
       }
      }
    }
  //Assign new items list to field items
    $field->items = $new_items;

    return $field->advanced_render($row);
  } else {
    return $field->advanced_render($row);
  }
}

```

# Answer
> 1 votes
I think you may have copied that code somewhat from a Drupal 6 version? The only problem is that the pattern for theme function signatures has changed in Drupal 7; only the `$vars` argument is passed in now, which is an array of named variables for the function:

```
function myTheme_views_view_field($vars) {
  $view = $vars['view'];
  $field = $vars['field'];
  $row = $vars['row'];

  // ...
}

```

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


# Question
Title: Convert Drupal error message to JavaScript alert
How I am able to do that?

I'd like to show the status/error messages in form of an alert using JavaScript instead of showing it on the screen.

# Answer
> 0 votes
It think the better messages module is for you.

---
Tags: status-messages
---


title: How to force users to log in with OAuth

text:
# Question
Title: How to force users to log in with OAuth
My site forces users to log in with a specific OAuth provider for some reasons. Users should not be able to log in using their username and password pairs. Only the site managers can have accounts independent of OAuth.

When first creating an account with OAuth, the 'pass' field is set to an empty string ''. My first question is whether it is the right and most secure way to prevent logging in using password.

The second question is about requesting new password via email. I implemented hook\_menu\_alter to customize `user` and `user/login` and to unset `user/password`. Now users cannot access `user/password`, I wonder if there is a bypass for it. This question is less important since almost all users would never bother with or even know the possibility of requesting new password.

# Answer
1. If you disable email notification of new accounts, the OpenID module will set a random password when users register. See openid\_form\_user\_register\_form\_alter(). If that is not what you want, you use `hook_form_alter()` to do the same thing under your desired conditions.
2. If you want to intercept `user_pass_reset()` so it cannot reset passwords, try using `hook_form_alter()` to add a form validation function.
> 2 votes

# Answer
This is what I did to disable Drupal's own login mechanism on Drupal 6 when I wanted to force users to log in through the Connector module instead: https://github.com/voxpelli/drupal-disabledefaultlogin

Never got around to release it on Drupal.org though and I'm not actively developing it anymore - but feel free to be inspired by it.
> 0 votes

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


# Question
Title: Implement a Facebook login without breaking the privacy
Like everybody knows Facebook ignores the privacy compleatly.

So I would like to allow users to login via Facebook without breaking their privacy or non Facebook users. Curriently I'm using the modules `Fbconnect`, `OpenID Selector`, `OpenID Selector for Drupal login` and `OpenID Selector for Facebook Connect`.

I want to allow the users to log in like in stack exchange. This works almost so like expected except the Facebook stuff. The plugin adds to everypage a stupid link to Facebook. So Facebook can spy my users. How can I avoid that?

Is it possible that I download the `http://connect.facebook.net/xx_XX/all.js` script and put it on my space? Or maybe to proxy the access and cache the file. Does anyone know if some of my ideas are forbidden by Facebook?

# Answer
I can suggest you a module called Janrain engage drupal.org/project/rpx , this does not add links, it helps you during the registration to collect the user data as well. Have a look to it.
> 1 votes

# Answer
If you really care about your users privacy then you shouldn't use a third party service like Janrain but instead communicate directly with the Facebook API. You can do that with the OAuth Connector module for Drupal 7 as it supports signing up and logging in through OAuth 2 API:s and specifically states that Facebook is one of the API:s that works with it.
> 1 votes

---
Tags: 7, users, social-network
---


# Question
Title: New custom content type: place image above body
I would like to create a content type in which an image is inserted after the title and before the body. When I add an image to the image field, that image is placed after the body...

# Answer
> 0 votes
On Drupal 7, you can change the placement of the image from within the interface by navigating to Structures-\> Content Types-\> *Name of your content type* and then clicking *Manage Display*. Drag the image above the body to show it first.

---
Tags: theming
---


# Question
Title: How do I display last five nodes, with the latest at the bottom using views?
I am creating a view which lists node titles for a specific node type. I want to display the 5 latest nodes with the latest at the bottom of the list.

If I sort using the post date criteria in an ascending manner, then the earliest 5 posts are shown. If I use descending, then the latest 5 are shown, but the the latest is at the top.

# Answer
> 2 votes
I'm fairly certain that Views does not support this. It's a somewhat frequent request for listing comments as well, but you can't add sorting after filtering/paging.

The easiest way is to change the view template to output the rows in reverse order.

# Answer
> 1 votes
You could use hook\_views\_pre\_render() to reverse the order of the rows before they get to the template but after sorting/paging. That way you can keep php logic out of your template files.

---
Tags: views
---


# Question
Title: Building something like an affiliate shop?
We want something very much like Amazon in that some providers define their products in a (site-)global catalog and customers can buy from this catalog. Customers and providers have the standard features expected from such a system (history, various reports etc etc).

A little peculiarity is that there are no payments or shippings in this system. We are responsible for *gathering* the orders from customers and notify the providers. The rest is not up to us.

Which modules do you think we should use to implement such a system ? (Drupal 6)

# Answer
> 1 votes
You've tagged this with ubercart and you're using Drupal 6 so this should be fine - http://drupal.org/project/ubercart\_marketplace

If you're not processing payments directly and have some 3rd party integration you're probably best off implementing a custom payment gateway and method using the hooks provided by ubercart than trying to track down a contrib module.

---
Tags: ubercart
---


title: Profile2 -> Update node on submit?

text:
# Question
Title: Profile2 -> Update node on submit?
I have a specific user role with a profile attached too them. Every user with this role has a corresponding node with the same information that can be found on the user's profile. Now I'm looking for a way to keep the two in sync, so if you change the user's profile, it would update the corresponding node as well. Is there a way to hook in to Profile2's form submit handler, or something similar?

# Answer
> 0 votes
Can't you just add your own submit handler to the form you're talking about rather than trying to override an existing one?

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


# Question
Title: Letting only user #1 pass all the validations of required fields when saving content
Is there any way I can let the user #1 save the content of some content type without validating required fields?

# Answer
You could probably use hook\_form\_alter and check if the current user is uid=1 then make each field not required any more.

That would be easier for most forms than messing with the actual validation functions and it would also make the UI reflect what is actually happening. You could even put a little message at the top of the form letting the user know that the form has been manipulated like that.
> 0 votes

---
Tags: nodes, 6
---


title: How can I redirect a user upon login?

text:
# Question
Title: How can I redirect a user upon login?
When users log in from the front page, they should be redirected to the dashboard; when they log in from other pages, they should be redirected to the same page they were.

I think that the Login Destination and the Login Taboggon modules can do this, but I am not sure how to use both of them.

# Answer
You can also use the rules module. You can add a rule which does a redirection after successfull login.
> 3 votes

---
Tags: 7, authentication-authorization
---


# Question
Title: Good Drupal distribution to start with Workflow?
Is there a better Drupal 7 distribution that I can start with, for an enterprise website which require to have workflow support?

# Answer
> 1 votes
Note: I don't know what you mean by "better", and also I don't know what you are comparing to.

NodeStream is my employers distribution. We base nearly all of project off it, and we try to keep much of our work in the open, to ensure that everyone can use it. We have support for the Workbench module and its workflow.

There was a presentation about how we work with NodeStream and built on top of it during the Barcelona devdays 2012, but as far as I can tell, no videos have been posted from there yet, so I can't link to it.

# Answer
> 1 votes
The problem with using a pre-defined workflow is that every organization is different. Some people need draft/pending/published, but want their own role names. Some people need multiple roles that can bypass different steps. Some people need to worry about moving backward through the workflow, while others don't. Some people need additional states, rather than the standard draft/pending/published.

My recommendation is to pick the distribution that works best for you, and then add on the Workbench module, and one or more of the related modules like Workbench Moderation and Workbench Access. Personally, I find this much easier to configure than Workflow. You should be able to get a basic workflow going in an hour or two.

---
Tags: 7, distributions
---


# Question
Title: Different cusztomizable user profile types
We need to add different customizable user profile fields in Drupal 6. How can this be accomplished?

# Answer
The Content Profile module is a popular solution for Drupal 6. It allows you to associate a node with a user, and the node creation process is automated when users are created. The node is a particular content type, and you can extend it with CCK. User profiles then get treated mostly like nodes.

For Drupal 7, users are fieldable through the UI (admin/config/people/accounts/fields), so very often an additional module is not needed. I have run into instances where different profiles are needed, and used Profile 2 to accomplish this.
> 0 votes

# Answer
You can try creating different content types and referencing those contents with different users
> 0 votes

---
Tags: 6, users
---


# Question
Title: user hook node update to attach files to a node?
im using the following code to upload an array of files when a node gets saved.

```
function mymodule_node_update($node){
 $result = $query;

 foreach ($result as $record) {
$url = ($record['src']);
$name_arr = explode('/', $url );
$filename = end($name_arr);
$filepath = system_retrieve_file($url, 'public://my_files/');

$file = new StdClass();
$file->uid = 1;
$file->uri = $filepath;
$file->filename = $filename;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;

$dest = file_default_scheme() . '://'.$filename;
$file = file_copy($file, $dest);
$file->display = 1;
$file->description = "";
 }
}

```

This uploads the files to my public directory, and creates an entry into files\_managed in my database.

But now how do I link those files to a filefield on the node im updating? I've tried variations of

```
  $node->field_file = (array)$file;

```

but nothing is working.

Thanks for any help

# Answer
> 1 votes
The field data has already been committed by the time `hook_node_update()` is called, so you won't be able to make any persistent alterations to field data in there.

Instead you could use `hook_node_presave()`, which is run before any data is written to the backend.

```
function mymodule_node_presave($node) {
  // Build up file object

  // Then add it to the node.
  $node->field_files[$node->language][] = (array)$file;
}

```

---
Tags: hooks, nodes
---


# Question
Title: Nothing returned from taxonomy_term_load function
The --very normal-- taxonomy\_term\_load() doesn't seem to be able to load entities within a custom menu callback. Yet I can access a profile entity, load fields, and get the field tids, but I get nothing from the taxonomy load function!

```
function mymodule_menu() {
  $items = array();
  $items['user/account-convert'] = array(
    'title' => 'My Page',
    'page callback' => 'mymodule_page',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mymodule_page() {
  global $user;
  $profile = profile2_load_by_user($user, 'my_profile_type');
  // Sanity check tid return. Success.
  echo $profile->field_profile_myfield[LANGUAGE_NONE][0]['tid'];
  // Term name returns nothing. The object just won't load.
  echo taxonomy_term_load($profile->field_profile_myfield[LANGUAGE_NONE][0]['tid'])->name;
}

```

This makes absolutely no sense.

I have even sanity checked outputting hard coded tid's like `echo taxonomy_term_load(1708)` after 100% confirming it's a valid tid value.

Additionally I followed the function tree up and tried calling `taxonomy_term_load_multiple` directly, and `entity_load` directly. All give me nothing.

Furthermore I can confirm the function is valid and available at that point with `function_exists`, and the lack of undefined function errors.

# Answer
> 4 votes
Probably, this is a Taxonomy Access issue.

See `taxonomy_access_query_term_access_alter()`.

(For the rest of the Internet, I only know this is the issue because Josh and I are working on the same codebase and I ran into the exact same issue in a completely different context.)

# Answer
> -2 votes
Try this one:

```
function get_tag_name($tid) {
    $query = db_select('taxonomy_term_data', 't');
    $query
            ->condition('t.tid', $tid, '=')
            ->fields('t', array('tid', 'name'));
    $result = $query->execute();

    foreach ($result as $row) {
        return $row->name;
    }
}

```

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


# Question
Title: How do I get the taxonomy term name of the current taxonomy term page.tpl.php?
Im on d7. Im trying to get the taxonomy term name of the the taxonomy page that I am on. Since Im not on a "node" page, I can't get it by the $node-\>tid. What should I do? Thanks.

# Answer
Try..

http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy\_term\_load/7

```
$term = taxonomy_term_load(arg(2));
$title = $term->name;

```

arg(2) should return the tid of the taxonomy page (taxonomy/term/tid).
> 23 votes

# Answer
I figured it out, heres what I did:

```
<?php
$termid = arg(2);
$term = taxonomy_term_load($termid);
$title = $term->name;
?>

```

Thank you @Kevin for your help.
> 6 votes

# Answer
Instead of using taxonomy\_term\_load() which is not working well every time, you can call:

```
function get_tag_name($tid) {
    $query = db_select('taxonomy_term_data', 't');
    $query
            ->condition('t.tid', $tid, '=')
            ->fields('t', array('tid', 'name'));
    $result = $query->execute();

    foreach ($result as $row) {
        return $row->name;
    }
}

```
> -4 votes

---
Tags: 7, theming, taxonomy-terms
---


title: access a text field by php

text:
# Question
Title: access a text field by php
I created a text field in my "content type". as I do with php to access this value? I would print it in a similar way:

```
 <?php print $submitted; ?>

```

in node.tpl.php and prevent it from being printed in an automatic way.

EDIT

I put this command in the file node.tpl.php:

```
<?php print $field_nazionalita_1; ?>

```

the result is:

```
Array([und] => Array(
   [0] => Array(
      [value] => francia
      [format] =>
      [safe_value] => francia
   )
  )
)

```

the result that I want is: francia

but only if I inserted a value in the field.

I know little php, you can help me?

# Answer
> 3 votes
You should read about the `field_view_field()`, something like this should work for you:

```
print render(field_view_field('node', $node, 'field_nazionalita_1'));

```

# Answer
> 0 votes
Depends what your field is called, but you can get it directly from any node object created by node\_load().

Do something like this and you'll see the structure of your node object which your field will be in:

```
<?php
  print_r($node);
?>

```

---
Tags: theming, 7
---


# Question
Title: Why are FAPI component names being duplicated
UPDATE: I've confirmed that the theme\_select function is being called, generates the expected html for the select element and that that output isn't actually being used.

---

I have a module which adds some functionality to webforms. As part of that I'm adding tabs when a webform is displayed so that our staff can do some fangling when necessary.

I have a tab being added:

```
//linker tab
    $items['node/%node/linker'] = array(
      'title' => 'Payment Linker',
      'page callback' => 'addLinkerTab',
      'page arguments' => array(1),
      'access callback' => accessLinkerTab,
      'access arguments' => array(1),
      'weight' => 100,
      'type' => MENU_LOCAL_TASK,
    );

```

which displays a form to do the initial setup of the modules functionality. This has been in place for over a year and works fine. It also includes:

```
$form['linkform']['components']['add']=array(
        '#type' => 'button',
        '#attributes' => array('class' => 'add-component'),
        '#value' => t('add'),
        '#ahah' => array(
          'path' => 'webform_checkout/link-editor/add-link-component',
          'wrapper' => 'item-holder',
          'method' => 'append',
          'effect' => 'fade',
          )
    );

```

I have a custom theme\_form\_element:

```
function bmc_zen_form_element($element, $value) {

  // This is also used in the installer, pre-database setup.
  $t = get_t();

  $output = '<div class="form-item"';
  if (!empty($element['#id'])) {
    $output .= ' id="' . $element['#id'] . '-wrapper"';
  }
  $output .= ">\n";
  $required = !empty($element['#required']) ? '<span class="form-required" title="' . $t('This field is required.') . '">*</span>' : '';

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' <label for="' . $element['#id'] . '">' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "</label>\n";
    }
    else {
      $output .= ' <label>' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "</label>\n";
    }
  }

  //not every element looks right with the description above it.
  If (array_key_exists('#webform_component',$element) && $element['#type']!='checkbox'){
      if (!empty($element['#description'])) {
        $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
      }
      $output .= '<div id="' . $element['#id'] . '">' . $value . '</div>' . "\n";
  } else {
    $output .= $value ."\n";
    if (!empty($element['#description'])) {
        $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
      }
  }

  $output .= "</div>\n";

  return $output;
}

```

and a custom hook\_theme\_Select

```
function webform_checkout_theme_select($element)
  {

    //if the array_parents is a 0 then we're in the ChooseForm form so
    if ($element['#array_parents'][0] == "linkform") {
      $elementName = "";
      //build the element name. we don't want to end up with a dangling dash
      $size = sizeof($element['#array_parents']);
      for ($i = 1; $i < $size; $i++) {
        $elementName .= $element['#array_parents'][$i] . '-';
      }
      $elementName = rtrim($elementName, '-');
    }

    $select = '';
    $size = $element['#size'] ? ' size="' . $element['#size'] . '"' : '';
    _form_set_class($element, array('form-select'));
    $multiple = $element['#multiple'];
    return theme('form_element', $element, '<select name="' . $elementName . '' . ($multiple ? '[]' : '') . '"' . ($multiple ? ' multiple="multiple" ' : '') . drupal_attributes($element['#attributes']) . ' id="' . $element['#id'] . '" ' . $size . '>' . form_select_options($element) . '</select>');
  }

```

I've just added a second tab

```
 $items['node/%node/formadmin'] = array(
      'title' => 'Admin',
      'page callback' => 'admin_tab',
      'page arguments' => array(1),
      'access callback' => accessLinkerTab,
      'access arguments' => array(1),
      'weight' => 100,
      'type' => MENU_LOCAL_TASK,
    );

```

Which adds two select elements to a form

```
  function orders_tab_form(&$form_state,$node) {
    $order_admin_form = array();
    $submissions = getAllSubmissionsForWebform($node->nid);
    $orders = getAllOrders();

    $order_admin_form['order_submission_linking_form']['submissions']['select']=array(
      '#type' => 'select',
      '#attributes' => array('name'=>'submissions-select'),
      '#title' => t('Submissions'),
      '#options' => $submissions
    );
    $order_admin_form['order_submission_linking_form']['orders']['select']=array(
      '#type' => 'select',
      '#attributes' => array('name'=>'orders-select'),
      '#title' => t('Orders'),
      '#options' => $orders
    );

    $order_admin_form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Link'),
    );
    return $order_admin_form;
  }

```

When the form is displayed the two select elements are named 'add-component' and 'add-maths' which means that they aren't showing in the form\_state when submitted.

```
<select name="add-component" class="form-select" id="edit-select"><option value="0">1727</option><option value="1">1728</option></select>

```

for example is the output of $order\_admin\_form\['order\_submission\_linking\_form'\]\['submissions'\]\['select'\]...

I'm utterly confused as to why the name is being set incorrectly.

Apologies for such a long question and thanks in advance for any suggestions.

# Answer
> 1 votes
The solution to this problem is that I am a massive idiot!

Often I've found when the answer seems to be "The framework with hundreds of contributors is wrong" then you've done something stupid and forgotten.

'Drunk Paul' has clearly been coding as I just found tucked at the bottom of some javascript

```
$("#edit-select").attr("name","add-component");
$("#edit-select-1").attr("name","add-math");

```

Which certainly explains my problem.

Now I just need to find out why I did that!

Apologies and thanks to anyone who has or will view.

---
Tags: 7, webforms
---


# Question
Title: Views slideshow overlapping right hand sidebar block
I'm using the default bartik theme and have created a views slideshow. I have a url for this and have marked this as the front page under the admin section. All great so far, in that when the (unauthenticated) user first visits the site they see the slideshow. Once they log in, I have a block that appears in the right hand side sidebar. However, the width of my slideshow is too wide in that it appears overlapped with this block on the right. What is the best way to address this? I could fix the width of the slideshow, but then that means I loose the flexibility to easily change the theme.

Also, can anyone point me to documentation that would help me understand why this happens?

Thanks in advance,

# Answer
> 1 votes
I found two ways of resolving this.

1. Permissioning the splash screen so that only non authenticated users can see it. That way, whenever anyone logs in they do not see the slideshow.
2. Use the corporate clean them - much better than anything I can develop!

---
Tags: blocks, javascript
---


# Question
Title: Why aren't nodes indexed when they are saved?
Why aren't nodes indexed when they are saved?

As we all know, `node_update_index` is invoked by `search_cron`, which means that the search index is only updated as frequently as cron runs.

I am curious why `_node_index_node` isn't part of the normal `node_save` process, eg

```
if ($node->status == NODE_PUBLISHED) {
  _node_index_node($node);
}

```

Is there a good reason for this? Since this function is defined by the node module itself, I don't see how it is a separation of responsibilities thing, nor can I think of a good reason for not doing this.

The related question would be, is is safe to wire up an action to fire when a node is created or updated?

# Answer
> 2 votes
I believe it is in the interest of scalability. Imagine you had a large, popular site with user-generated content. Imagine you had users saving a node (say, posted a question or answer) every 20 seconds. Imagine a node being indexed as well as submitted every 20 seconds. The site would become unusable very quickly. So it's much better to allow the indexing to happen independently of node submission.

---
Tags: 7, nodes, search
---


# Question
Title: Custom code field API no field showing in Manage Fields
**In short**: I want to create a field 'Referenced Content' that links to /node/add/content-type/. My actual question is: Why is there no option ( see my `hook_field_info()` function) in my select list in Manage Fields?

Basically I'm just learning the beginnings of module development and I'm trying to make small steps. So the first thing I want working would be to add a field width a widget that would be part of the configuration options in in `admin/structure/types/manage/content-type/fields`

I looked at the field\_example module that is part of the examples module and here's my code so far (why I think custom code is needed look below).

```
<?php
function entityreference_add_new_field_info() {
  return array(
    // We name our field as the associative name of the array.
    'add_referenced_content' => array(
      'label' => t('Referenced Content'),
      'description' => t('A button that allows content author to add new content that is
          referenced.'),
      'default_widget' => 'entityreference_add_new_button',
      'default_formatter' => 'entityreference_add_new_button',
    ),
  );
}

function entityreference_add_new_field_formatter_info() {
  return array(

    'entityreference_add_new_button' => array(
      'label' => t('Simple HTML link'),
      'field types' => array('entityreference_add_new_button'),
    ),
  );
}

function entityreference_add_new_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'entityreference_add_new_button':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#type' => 'html_tag',
          '#tag' => 'a',
          '#attributes' => array(
            'href' => '#',
          ),
          '#value' => t('This button is currently linking to @code', array('@code' => '#')),
        );
      }
      break;
  }
   return $element;
}

function entity_reference_add_new_field_widget_info() {
  return array(
    'entityreference_add_new_button' => array(
      'label' => t('Button to make new referenced content'),
      'field types' => array('entityreference_add_new_button'),
    ),
  );
}

```

I left out the validate functions and the `is_empty()` functions thinking that they have no influence on showing up in the Manage Fields configuration page or not.

In case you're wondering why I'm thinking custom code instead of just adding a field with some markup here's the end goal:

An example is that there is a contenttype 'transfer order' that is referenced to contenttype 'transfer file'. There is a one to many relationship between a transfer file and transfer orders respectively. I have a view setup for the content type 'transfer file' that lists it's title, date and edit field. Added to this view, I will be needing a field that is a link to a node edit page. Like this `node/add/transport-order/<nid>`. needs to be the id of the transfer order content type. The idea then is that fields in the new transfer order would be already filled in with content that comes from a transfer file that is referenced.

note: I posted another question where I initially thought I needed to do something that the references dialog module would already do. So I guess now this doesn't seem to be the case and should call for some custom code.

Update: So I tried reducing my code to just the hook\_field\_info() to feed the field\_create\_field() function which should get me started getting the field into my Manage Fields page as a babystep.

code in my .module file would be like this:

```
function entityreference_add_new_field_info() {
  return array(
       'entityreference_add_link' => array(
          'label' => t('Entityreference link'),
          'description' => t('Entityreference link'),
          'default_widget' => 'entityreference_link_widget',
          'default_formatter' => 'entityreference_link_formatter',
      ),
    );
  field_create_field('entityreference_add_link');
}

```

This doesn't put anything in my Manage Page table under 'Field' (Should be an option in my drop down list, right?).

# Answer
> -1 votes
The only thing required for your field to show up in your "Manage Fields" page is to create a field with field\_create\_field(), you may define the field using hook\_field\_info().

It can be cumbersome to those settings arrays from scratch. I would recommend this approach. Build your field using your field UI, and install Devel.

Then view this blog post: http://steindom.com/articles/exporting-and-creating-field-definitions-drupal-7

What you really care about in that blog post is: `field_create_field($info_config);`

So in short:

* build your field using drupals FieldUI (Manage Fields -\> Add field ....)
* export the arrays to code via the above blog post
* copy that code into your module install() or enable() function.

---
Tags: 7, entities
---


# Question
Title: Save values from Commerce Profile to User Profile with Rules?
The response to this question indicates that the solution is to save values from the Commerce Profile into the required field(s) of the User Profile using Rules. I can't figure out how to do this!

I created a new Rule, triggered by event "After saving a new commerce customer profile" (though I might well need to integrate this rule into the Commerce Profile creation rule for it to work with required fields. For now, I've just removed the requirement.) Here are the actions that I've picked out as looking like good candidates for doing what I want:

* Data
    + Add a Variable (Does this mean save a variable with a value, or just instantiate a variable? Where?)
    + Add an Item to a List (What list? Where?)
    + Set a Data Value (How is this different from "Add a Variable"?)
* Entity (Are User profiles Entities?)
    + Create Entity (Use this to create the new User profile?)
    + Save Entity (Will this save values to the Entity?)

Are any of these going to do what I want? Am I on the wrong track entirely?

Thanks.

# Answer
In order of asking:

* Data

+ 'Add a Variable' saves data to the `{variables}` table in the database, to be used with the standard `variable_get()` method.
    + 'Add an Item to a List' will let you pick an entity and list-type field in the next step to initialise/add another item to (this might include a field with multiple values allowed, say).
    + 'Set a Data Value' will let you set the value for a single, arbitrary field/property (usually as part of an entity). It's different from 'Add a Variable' in that it set the data value on the entity, and doesn't add it to the `{variables}` table.
* Entity (profiles provided by the core profile module are not entities, if you're using the Profile2 module, then they are).

+ If you're using Profile2, yes.
    + If you're using Profile2, you'll be able to use it to save the entity *after* you've used the 'Set a Data Value' to set the value.

Looking through the profile.module and user.rules.inc files I can't see any built in support for the profile module; it stores its data in custom tables and I can't find any glue code that would suggest support's been added for rules (it's worth double checking this though, I could easily be wrong).

If it's not too late on in the build it might be worth having a look at Profile2; as each profile is an entity you'll get rules support built in automatically.

The other thing you could do is write the profile rules functionality yourself (implementing `hook_rules_action_info()` etc.) but that would be quite a bit more complicated.
> 1 votes

---
Tags: commerce, rules, users
---


# Question
Title: How to add advertisement node at the end of Slideshow
I have three content type 1) Slideshow 2) Slides 3) Advertisement

While creating slideshow we can assign slides to slideshow with nodereference field. We have created a views for slideshow on the view page of slideshow we are displaying all the slides one by one and there are two links next and previous. Now I want to add a single Advertisement at the end of this slideshow view.

I tried hook\_views\_api() and hook\_views\_query\_alter(). Content type slides and advertisements have different fields.

# Answer
> 1 votes
slides are usually images or maybe node bodies (html). It doesnt really matter that advertisments have different fields. I had some code in Drupal 6 you could adapt to D7 or your needs, look into hook\_views\_pre\_render() ...

You simply want to load your advertisement node(s) before the view is rendered and add them to the end of the slideshow ... see below.

```
//d6 example
function MYMODULE_views_pre_render(&$view) {

  if ($view->name == 'your_view' &&
    $view->current_display == 'slideshow_xyz') {
    // Insert something to the end of the view results.
    // For example another "node" or advertisement.
    $some_node = node_load(array('nid' => 456));
    // make a fake view row item with your advertisement.
    // you should create all fields used in "slides" from your
    // advertisement node data.
    $advertisement_item = new stdClass();
    // add your advertisement fields as fields being used by the Slide view.
    $advertisement_item->a_field_views_is_using = $some_node->advertisement_field_1;
    //  ... add all other view row items you are using ....
    // make this advertisement "row" in the results appending to the view results for slides.
    array_push($view->result, $advertisement_item);
  }
}

```

---
Tags: nodes, views
---


# Question
Title: Using Drupal 6's form ahah to have one dropdown field update the values of a second dropdown field
I am working on a pair of form fields the directly effect one another. Specifically the problem I am dealing with is that we have thousands of groups users can join on this website that I have been working on. We are creating some administrative analytics forms for the site. Part of those forms is filtering by group.

The problem is that most of the people don't know the name of a group off the top of their heads, only what it starts with. So instead of using auto-complete we came up with two dropdowns. The first contains the options A through Z, letters of the alphabet which the group names begin with. The second dropdown contains all of the groups beginning with the selected letter.

The concept is simple enough and we were able to implement the AJAX pretty easy with jQuery. But this causes validation errors. After some research I found that this has to do with Drupal form caching. The solution is to use the ahah functions.

The problem with that is that all the instructions I have found so far deal with ahah actions for the specified field updating itself, not another field. So I am trying to figure out how to get the list of letters to update the group list using ahah and registering the new values with the form cache.

One solution I found was to simply load all the values on the page in a hidden dropdown and then just load up those in the set in the visible one as needed. But that creates a bunch of problems because the client uses almost exclusively IE and we have seen IE choke when given huge lists like that. Especially with the lists stored in JavaScript. So we need a light-weight solution.

Any thoughts? Ideas?

# Answer
There's comprehensive example code in the Examples module that shows how to do this.

In the dependant\_dropdown.inc file of the `ahah_example` module, you'll find an example form that does exactly what you're looking for. It's very well commented and should guide you through the process pretty well.

There's also a companion tutorial for the `ahah_example` module which would be worth looking it as it has more code examples.
> 2 votes

---
Tags: 6, forms, ajax
---


# Question
Title: In add filter criteria "user" not coming from FILTER list in add views
I am following the book "The Definitive Guide to Drupal 7" where I am trying to add a new view. But when I tried to add filter,I can't find the User in the FILER list . I am very beginner to Drupal,though I know PHP .

# Answer
It depends on what kind of view you're creating. You are probably working on a view for content. So the filters are limited to those related to content. You can add a relationship "Content: Author" (Relate content to the user who created it.) under "Advanced Options" to add more filter criteria to the filter criteria list (User will show up in the filter list then, too).

Or you try creating a view for users.
> 5 votes

# Answer
You first need to go to "Add relationships" to Content: Author Now go back to "Add filter criteria" and you will see the user filter and a lot more user information you can use.

This was a change from Views 2 to Views 3 I think.
> 4 votes

---
Tags: views
---


# Question
Title: Migrate module problem with migrating images - D7
I am attempting to migrate images from a directory into an image field. All of my other fields are migrating correctly. No errors are being thrown, the database values do not appear and the image is not copied into the destination directory.

```
// Image migration
// basic mapping of destination field and source field
$this->addFieldMapping('field_figurae_image', 'highresfile');
// Directory where source images are located
$this->addFieldMapping('field_figurae_image:source_dir')
     ->defaultValue(drupal_get_path('module', 'migrate') . '/matrixmigrate/matrix_libary');
// Directory that source images will be copied to
$this->addFieldMapping('field_figurae_image:destination_dir')
     ->defaultValue('sites/default/files');

```

I believe my syntax is at least close to correct here. It is based on the "BeerNodeMigration" example. I had difficulty with Taxonomy migration that had very similar results. It turned out that I had another piece of code that was not formatted correctly. This is the only code I have related to images, is there an additional step that I'm missing?

Thank you for your time.

-Mitchell

# Answer
> 1 votes
I think my source\_dir path was incorrect. I used the following and it worked:

```
// Image migration
// basic mapping of destination field and source field
$this->addFieldMapping('field_figurae_image', 'highresfile');
// Directory where source images are located
$this->addFieldMapping('field_figurae_image:source_dir')
     ->defaultValue(drupal_get_path('module', 'matrixmigrate') . '/matrix_library');

```

The major difference here is that I used my sub-module instead of the migrate module itself to grab the path. I also played with permissions in various directories. I think one of those two things did it. I also dropped the destination directory since it defaults to your Drupal file directory.

---
Tags: media, migrations
---


title: Add attachments to mail

text:
# Question
Title: Add attachments to mail
How I send a mail with attachments using the mimemail module? In drupal 6 it was using the function:

```
mimemail($sender, $recipient, $subject, $body, $plaintext = NULL, $headers = array(), $text = NULL, $attachments = array(), $mailkey = '', $send = TRUE)

```

But I am not able to figure out how to do this in drupal 7.

# Answer
Try this code. I'm using it with backup and migrate module

```
$module = 'backup_migrate';
$key = microtime();
$language = language_default();
$params = array();
$params['attachments'][] = array(
  'filepath' => $attachment->path,
  'filecontent' => 'My attachment.',
  'filename' => $attachment->filename,
  'filemime' => 'text/plain',
);

$from = $mail->from;

$send = FALSE;
$message = drupal_mail($module, $key, $to, $language, $params, $from, $send);

$message['subject'] = t('Database backup from !site: !file', array('!site' => variable_get('site_name', 'drupal'), '!file' => $attachment->filename));
$message['body'] = t('Database backup attached.') ."\n\n";

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);

// Format the message body.
$message = $system->format($message);

// Send e-mail.
$message['result'] = $system->mail($message);

```
> 4 votes

---
Tags: 7, emails
---


title: How to theme Views Bulk Operation Pages

text:
# Question
Title: How to theme Views Bulk Operation Pages
In views bulk operations, you can select fields and then edit them by clicking on "Modify Entity Values".

When you do this, a screen appears asking you to select the entities you wish to modify and the values you wish to set. **Is there a way of using a custom template to theme this screen?**

---

---

**Additional Info:**

The top part of the screen lists provides check boxes for all the entities the user can edit. The user has to tick a check box to edit an entity. The bottom of the screen lists all the values that can be set.

I would like to use Jquery so the values on the bottom only appear when the corresponding check box at the top has been ticked. Is this possible?

# Answer
if I understand you correctly, I think you should look at preprocessing the VBO form. You can then theme it as you would any other form.
> 0 votes

---
Tags: theming, views
---


# Question
Title: Error sending Drush commands to remote host
I have Drush 5.2 installed on my local dev system and my remote host, which has staging and production sites. I have aliases for all three sites, and am able to use `rsync` and `sql-sync` on both systems with no problems.

From what I understand, I'm should also be able to issue commands to the remote system such as

```
drush @stage vset preprocess_css 0

```

Whenever I try to do something like this, it fails. For instance, if I run `drush -d @stage status`, I get:

```
Bootstrap to phase 0. [0 sec, 3.7 MB]                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.93 MB] [bootstrap]
Loaded alias @stage from file /path/to/local/drupal/sites/all/drush/aliases.drushrc.php [0.01 sec, 3.94 MB]                          [notice]
Cache HIT cid: 5.2-commandfiles-0-c87dbef8e3e302e07ccdc024aee7fbbd [0.16 sec, 3.95 MB]                                                                      [debug]
Begin redispatch via invoke process [0.19 sec, 8.77 MB]                                                                                [notice]
Backend invoke: ssh -o PasswordAuthentication=no user@my.host.com 'drush  --invoke --debug                                                 [command]
--root=/path/to/remote/drupal/ --uri=http://stage.mysite.com --verbose status 2>&1' 2>&1 [0.23 sec, 8.8 MB]
executing ssh -o PasswordAuthentication=no user@my.host.com 'drush  --invoke --debug --root=/path/to/remote/drupal/      [notice]
--uri=http://stage.mysite.com --verbose status 2>&1' 2>&1 [0.23 sec, 8.8 MB]
Calling proc_open(ssh -o PasswordAuthentication=no user@my.host.com 'drush  --invoke --debug --root=/path/to/remote/drupal/ --uri=http://stage.mysite.com --verbose status 2>&1' 2>&1);
bash: drush: command not found
Invoke process is complete [1.34 sec, 8.79 MB]

```

# Answer
> 5 votes
In order for remote commands to work, you must make sure that drush is in your PATH. This is often done by putting something like the following in a line that bash will source when it starts up:

```
export PATH=$PATH:$HOME/local/drupal/drush

```

A lot of folks put a line like this in their ~/.bashrc file, but note that on a lot of systems, this file begins with a line similar to the following:

```
[ -z "$PS1" ] && return

```

This means that everything below the line above will only execute when bash is running interactively; if you put drush in your PATH after this point, you will be able to run drush when you log in to your remote machine, but not when you attempt to call drush remotely (e.g. via drush, as shown above).

There are many solutions to this problem.

1. Set your PATH before .bashrc bails out.
2. Make a symbolic link to your drush executable from a directory that is always in your PATH (e.g. `sudo ln -s /path/to/drush /bin`)
3. Set %drush-script as described in examples.aliases.drushrc.php.

---
Tags: drush, deployment, staging
---


# Question
Title: using Feeds Xpath Parser to import RSS feeds
I am trying to import a Wordpress feed with images (e.g. http://blog.objet.com/feed/) into Drupal 7. I've installed the Feeds XPath Parser module and read the documentation but I am still having the following issues:

1. The document is XML, but firefox shows it as XHTML. Whic parser to use? XML Parser or HTML Parser?
2. What is the selector (context) of the root element? I've tried 'xhtml', '/xhtml', 'xhtml:meta', '/xhtml:meta', 'item', '/item' (with both XML and XHTML parsers) but no elements are getting imported (the feed was imported correctly before I've installed the 'Feeds XPath Parser' module).

Updates:

1. I was also trying to add "//item" as a selector, this time I got one item, with one image, while no other items being imported.

# Answer
> 1 votes
You have to fully understand the XPath queries logic to use the parser. It's very powerful once you get it, but it needs a bit of practice.

Here is a good starting page : http://www.w3schools.com/xpath/

Note that you have two parts in the UI for the queries :

* One to set the context, which is the element all further queries will be run from
* One for each field

The context element depends on your document and the logic of the data inside. Usually, you set the context each 'entity' or node is saved in, and then query fields or attributes for the different fields.

For example, if you have a 'Thing' entity like this :

```
<Thing>
<id>1</id>
<name>Name One</name>
</Thing>
<Thing>
<id>2</id>
<name>Name Two</name>
</Thing>

```

... you would set the context to `/Thing` and then each field query to `name` and `id`. You also have a syntax to query attributes.

Also, be aware Feeds is only compatible with XPath 1.0 syntax.

# Answer
> 0 votes
Your link is xml, but firefox renders it as html for the user's convenient. Open the link in chrome and you will see the xml. Look at the xml and you will identify the rest of the nodenames.

Your context is `//item`

---
Tags: feeds
---


# Question
Title: Javascript aggregation issue with new server
I have a new VPS Host and have cloned my existing live site from my current VPS Host. On the new host, there is an issue with JS aggregation and I am hoping someone might recognize what this is and how to solve it.

Generally with JS aggregation set at `/admin/config/development/performance`, Javascript breaks sitewide, both front end and backend, logged in and non-logged in. I checked permissions and the JS directiory at `/sites/default/files/js/` and it seems fine, files are writing to this directory (both the JS files and the GZipped ones).

When I view the raw code of any of these files, the code is fine (not corrupt). I have also tried switching this off, clearing cache, switching back on, clearing browser cache and even deleting the directory which Drupal did and then recreated without any issue. I checked my PHP info file (5.2.17) and it shows this under `PHP Variables` `_SERVER["HTTP_ACCEPT_ENCODING"] - gzip,deflate,sdch` so that seems ok. However my old server's PHP info file also had `gzip,deflate,sdch` under an additional heading called "`HTTP Headers Information`".

But here is the real tell-tale, I think, when I view the code of my webpage with Chrome web inspector and look in Console, I see as many JS errors as there are aggregated files. (5 or 6 I think). The error is: `Uncaught SyntaxError: Unexpected token ILLEGAL` If I then view the corresponding JS file, I see this:

So somehow, the aggregated JS files are turning into gibberish characters and the errors are thrown. I have spoken with my webhost and we tried some things but nothing worked. They had me put this code into .htaccess but it did not work:

```
[root@host ~]# httpd -L | grep deflate
DeflateFilterNote (mod_deflate.c)
DeflateWindowSize (mod_deflate.c)
DeflateBufferSize (mod_deflate.c)
DeflateMemLevel (mod_deflate.c)
DeflateCompressionLevel (mod_deflate.c)

```

Also I was not exactly sure where in .htaccess to put it. (under `<IfModule mod_headers.c>` perhaps?) At any rate this did nothing to help matters no matter where I tried that code. I feel like this is a bit of a needle in a haystack and might be tricky to fix but I am curious if anyone recognizes what might be going on so i can fix it.

\** I should also note that litespeed Server is running on top of this so not sure if there are nay issues with that. I have not looked into this yet.

# Answer
It's likely that your web server isn't sending the correct Content-Type or Content-Encoding header for compressed files.

Adding one of these to your httpd.conf file should solve the problem:

```
AddType application/x-gzip .gz .tgz

```

or

```
AddEncoding x-gzip .gz .tgz

```

There should be comments in your httpd.conf file that will help you determine which one's most appropriate for your situation (search for `<IfModule mime_module>` in that file if you're interested).
> 5 votes

---
Tags: javascript, caching, css-js-aggregation
---


# Question
Title: Can't Review Order, button loops back to checkout form '/cart/checkout'
I'm having a problem which is prevent me from reviewing my order after completing the checkout form. Once I click on "Review Order" the page essentially refreshes itself because of the loop. Others with the same issue have varying solutions, I've tried a handful so far without any luck.

It seems the issue may be with the session being lost somehow, but I'm not sure what could be causing this. I haven't changed anything related to ubercart in months, yet the problem appeared days ago. Any suggestions or work arounds would be greatly appreciated.

I'm using PayPal Website Payments Standard, Drupal 6.2, Ubercart 6.29.

Thanks.

# Answer
> 0 votes
Thanks to David's response, I was inspired to investigate my upgrade from uc 2.8 -\> 2.9 and ran the update.php script. It seems it was not run at the time of the upgrade, so now that it has the problem is solved.

---
Tags: 7, ubercart, debugging, payment-gateways
---


# Question
Title: How to call php snippet which is save as basic page?
I have a php code as below:

```
$("#tbMGroup tr.odd").click(function() {
              $("#m_id").val($(this).attr("m_id"));
              $("#form1").first().attr("action", "search.php");
              $("#form1").submit();
            });

```

but,
I have add search.php to a basic page. now, these code need to call search.php when mouse click, I don't know how to call search.php snippet, because search.php now is not a independent file, it is a snippet. Thanks for your help...

# Answer
I figured out the way, just changed my snippet to:

```
$("#tbMGroup tr.odd").click(function() {
  $("#m_id").val($(this).attr("m_id"));
  $("#form1").first().attr("action", "/node/nid");
  $("#form1").submit();
});

```

It works.
> 0 votes

# Answer
I think you should use hook\_menu to define the path the drupal way and rewrite your form using drupal FAPI. This gives you a clean system.
> 0 votes

---
Tags: forms
---


# Question
Title: Get shipping and billing information from rule
I am using the Drupal commerce module. I want to write a PHP script to execute on order completion, and I want that script to update an external database with the shipping information. How would I go about doing this?

I have already setup a rule to execute PHP code on order completion, and I am given the variable `$commerce_order`, but I don't know what to call to get out the customer shipping information. I have tried to email `var_dump($commerce_order)` but it does not give me anything.

How can I get a list of the fields? Am I on the right track?

# Answer
> 0 votes
The shipping information isn't directly stored on the order. The only way you have of figuring the shipping details is to look at the line items at `$order->commerce_line_items` one or more of them will be shipping line items, which can tell you about the shipping details.

# Answer
> 0 votes
To write to a second DB you most likely need some custom code. Therfore I sugest to write your own rules action (see http://drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook\_rules\_action\_info/7)

I'd start with the 'order is payed in full' rules event since it gives you the order and payment transaction object in the $data parameter of the action.

Have a look at the commerce\_email module to get a code example for finding the line items of an order.

---
Tags: rules, commerce
---


# Question
Title: how can i add a subterm of taxonomy in code
```
$vocabulary = (object) array(
'name' => st('A'),
'description' => st('A'),
'machine_name' => 'user_a',
'help' => 'test for subterm',
);
taxonomy_vocabulary_save($vocabulary);

$user_a=array(st('A'),st('B'));

$user_a_vid=db_select('taxonomy_vocabulary', 'tv')
  ->fields('tv', array('vid'))
  ->condition('machine_name', 'user_a')
  ->execute()
  ->fetchField();

foreach ($user_a as $name) {
    $term = new stdClass;
    $term->name = $name;
    $term->vid = $user_a_vid;
    taxonomy_term_save($term);
 }

```

i have two vocabulary A and B

and i want to add sub-term of A and B

A have sub-term 1,2 B have sub-term 3,4

how can i do that in code?

Thanks for reading my question~thx~

# Answer
Yeh~

i found out,this code can fix all the problem

```
$term->parent = $parent_tid;

```
> 1 votes

# Answer
Depending on your use case, you may be able to use the Taxonomy CSV module. This module allows you to create a CSV file and import taxonomy vocabularies (including subterms/hierarchy structures).
> 0 votes

---
Tags: taxonomy-terms
---


title: Overriding data in a block

text:
# Question
Title: Overriding data in a block
I have a block manually created through the drupal admin panel.

I would like to override it in order to implement in it an array of data with it's corresponding html.

Is there an easy way to do this?

I also could create the block programmatically with the hook\_block instead of using the admin panel.

I don't mind doing it either way, which way do you recommend?

# Answer
> 1 votes
you can use array in static block(created through admin panel) also by choosing text format to "php Code". What exactly, you want to achieve ?

---
Tags: 6, hooks, blocks
---


# Question
Title: Social Networking buttons in a list of teasers generated using views
I have generated a list of blogs with title and teaser , with a pager also , using views. I need to display social buttons like share on Facebook, twitter etc on each items of the list. How can this be implemented?

# Answer
> 1 votes
Download the ShareThis module. This does what you need.

Here is a quote about it (from the module's project page):

> Integration with the ShareThis social bookmarking utility on selected node types.
>
> The code for this project was based on the original share project for Drupal 5.x. The code for this project has been trimmed down to only work with the ShareThis system, and not require any additional modules to work properly.

---
Tags: views, social-network
---


title: Add multiple items to cart

text:
# Question
Title: Add multiple items to cart
Is there a module or a detailed how-to out there that can help with creating a form to add multiple products to the cart at once for Drupal 7, Ubercart 3.0?

# Answer
One way of doing it is by using the Views Bulk Operations module. There is a patch which has recently been committed and offers the "Add to cart" action over here: http://drupal.org/node/1553700

Once your view is built (fields only) you can add a Content VBO field and choose the Add to cart action from there. In theory, redirection to the cart can be done by including the ?destination=cart parameter when calling the View which should be honored once the form is submitted. However, at the moment this appears to only add one item and redirecting rather than all items that have been selected.
> 3 votes

# Answer
This should help you. The code as it is below can be put in a template file or function. However when using it in a function you probably want to return the form and add it rendered to some html.

```
$form = drupal_get_form('multi_add_form');

function multi_add_form() {
  $form = array();

  // Make the products array in the form a tree.
  $form['products'] = array(
    '#tree' => TRUE,
  );

  // Use an array of product nids to build the form.
  $nids = array(1, 2);

  // Add a quantity field for each product. from 0 to 10
  foreach ($nids as $nid) {
    $node = node_load($nid);

       $x = 0;
   $options = array();
   while ($x <= 10) {
      $options[$x] = $x;
      $x++;
   }

    $form['products'][$nid]['qty'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#title' => t('Amount'),
      '#default_value' => 0,
    );
  }

  // Add an add to cart button.
  $form['add_to_cart'] = array(
    '#type' => 'submit',
    '#value' => t('Add to cart'),
  );

  return $form;
}

function multi_add_form_submit($form, &$form_state) {
  // Loop through the products array.
  foreach ($form_state['values']['products'] as $key => $value) {
    // The key is the product nid, the value holds the qty.
    if ($value['qty'] > 0) {
      // Add the item to the cart if the quantity was increased.
      uc_cart_add_item($key, $value['qty']);
    }
  }

  // Display a message and redirect to the cart.
  drupal_set_message(t('Your cart has been updated.'));

  $form_state['redirect'] = 'cart';
}

print drupal_render($form);

```
> 1 votes

---
Tags: ubercart
---


# Question
Title: Showing list of nodes related to logged in user using views
I have some content of content-type "mockup". The "mockup" content-type has a field that references a user (so when I create a mockup, I can select a user for it to "belong" to).

For some reason, I can't figure out how to use views to get all "mockups" that belong to the logged in user. I thought it would be in "contextual" but I don't see anything like that.

I don't want anyone to be able to view the node unless they are the "related user", is this a "views" thing or a "permissions" thing?

# Answer
I'm not sure about the details of your use case, but it might be easier to set the author of the node to the user rather than setting up a field with a reference.

You can set the author manually if you have administrator permissions. You could also use the Rules module (via the "Set a data value" action) to do so automatically.

If you use this method, you can simply set the permissions for "View own content of type ABC" and "View all content of type ABC" that are provided by default to limit access.

For your view, you can add a "Contextual filter" of "Author".
> 0 votes

# Answer
You can do this in many ways. One of them is to set a contextual filter Content: Author uid . You can also add relationship to add more information. You can also give the access permission as per specific role.
> 0 votes

---
Tags: nodes, users, views
---


title: Temporary Drupal hosting

text:
# Question
Title: Temporary Drupal hosting
I'm not entirely certain that this question belongs here but here goes. I've built a pretty basic Drupal site for a department at my University but now I need to migrate it from my laptop to the public. In order to do that I have to jump through a -lot- of hoops with the ITCS department of my University but the site needs to go live pretty soon (within the next 4 days or so) because it's currently hosted on my laptop and I'm leaving the country.

So, what I was wondering is: is there somewhere that I can put this thing for free for a while so that the folks I'm working with can get used to it and show it off (it's for grant purposes) while I work with ITCS to get it up on University servers?

I can't really do it and they don't have any one who can show them how (I'm working remotely) so it's been a pretty big hassle getting this thing off the ground.

Thanks!

# Answer
> 2 votes
Pantheon will allow you to set up a dev site on their servers for free. This will not support very many users unless you're willing to pay but is probably sufficient for a demo.

# Answer
> 3 votes
I'd look for cheap shared hosting. Make sure you get PHP and MySql and some kind of temporary URL.

# Answer
> 0 votes
hey use this for free hosting....

http://www.000webhost.com/554256.html

This is awesome you can host any drupal website having data upto 1500 MB. But they support PHP 5.2 for free hosting. If you need 5.3 then go for paid...

---
Tags: database
---


# Question
Title: change the body and the title of my content type by css
I'm using the zen theme I would like to customize with css, the "content type" that I created. Set a different font for the title and body. What should I do?

# Answer
> 1 votes
1. Install the Firebug and find the appropriate class or id.
2. Look for kick start inside the zen theme and follow the instructions to crete a sub theme.
3. Adjust the CSS found with firebug to your needs.

After all this is basic drupal theming stuff. Check this out to get a bigger picture.

---
Tags: theming, 7
---


# Question
Title: Should I manually upload these large files?
I have about 10 large zip files (20Mb) which need to be uploaded to a site once, and once only. I then want to be able to download them from a block in a sidebar (i.e. not from the main content).

I was thinking that the easiest way to do this would be manually upload them to the site (via ftp), then hardcode links in the blocks to reference the file location. Does this sound OK? Does it violate any drupal rules?

The reasons I wanted to do it this way, rather than through the file UI or another module, are that I don't have to worry about the php.ini upload\_max\_filesize and post\_max\_size. Also, I won't have to work out how to use the drupal UI to put a link in a block.

What do you think?

# Answer
> 2 votes
Manually uploading the files and hardcoding the links into a block, Shouldnt be a problem.

You Could also check this module out :) Download File Module

---
Tags: files
---


# Question
Title: Translate label of Comment Body with String Override
I'm using i18n and string overrides for translating fields in the front end. I opened up the comment-section for several content types and it's working great. The only thing is: I can't find a way to translate "Comment" to german to "Kommentar".

I just found out, that the Comment-Form doesn't get a specific language-tag. So it is und(efined) which leads to the english word Comment.

The easiest but a little dirty way to fix that is to translate it by hand with the hook\_alter\_form in the template.php

Is there a more cleaner way to do that?

Thanks

# Answer
Yes there is you should try out Localization client

This would help you out, and translate the content in t()
> 1 votes

---
Tags: 7, i18n-l10n, string-overrides
---


# Question
Title: How to add [google ads] in between the views slideshow after completing four slides
Any one can explain shortly ? How to add \[google ads\] in between the views slideshow after completing four slides .presently am having gallerific slideshow and slides are from specific content type. Thanks by advance.

# Answer
Unlikely I don't know this module but I think you should look for the tpl.php. I've done something similar for a normal view were after 7 node it should show an empty box. In the file views-view-unformatted.tpl.php there is this script that generates the rows.

```
<?php foreach ($rows as $id => $row): ?> #for all the node, do this
  <div class="<?php print $classes_array[$id]; ?>"> # open div with the classes view-row, view-row-odd, view-row-1
    <?php print $row; ?> #print the node
  </div>
<?php endforeach; ?>

```

I've changed in this way

```
<?php
$counter = 0;#it counts the row
 foreach ($rows as $id => $row) {
 $counter++; # add one to the counter
 print '<div class="'.$classes_array[$id].'">';
 if ($counter == 8) { # the views-row-8
   print 'Something'; #it prints "Something" instead of the node.
 }  else {
  print $row;
  }
  print '</div>';
  }
  ?>

```

It will print normal row if the row is not the number 8.

Try to adapt this code for yout needs. You need to find the right tpl.php for the slideshow, copy the file and put it into your theme folder inside template. You should be able to rename it taking the name from the view panel clicking on "theme", so the other slideshow view will not be affected.

Let me know
> 0 votes

# Answer
Use the HTML code of google adds . Copy and paste HTML code of google adds in the body of new content. You can also use ck editor.In views also select body field along with image field. Also add global php in which add a if else conditon to show either image or body.
> 0 votes

---
Tags: views
---


title: How we design themes using drupal

text:
# Question
Title: How we design themes using drupal
I am new to drupal cms, can any one tell me how we design themes using drupal.

# Answer
> 1 votes
You can try creating sub-themes by following the procedure given here. Modifying is easier then creating a new theme from scratch(my experience). For this you will need to select a base theme, which you can download from Drupal.org. The most common theme which is used to create sub-themes is Zen.

Here is nice tutorial which will help you get started.

# Answer
> 0 votes
If you are using Drupal 7 you can use Omega theme. It's an html5 template with responsive grid. it includes media queries (it helps you building different layout for screen and mobile device. Here you can find the documentation.

You can also follow indrock's suggestion. Zen now has got the HTML5 as well.

---
Tags: theming, hooks
---


# Question
Title: Filtered HTML Text format without an editor
How can I set up the following:

* Administrator should be able to use Full HTML with an editor window in Nodes.
* Users should be able to use Filtered HTML in Nodes without an editor - just the markup.
* Everybody should be able to use Filtered HTML in comments via markup - no editor.

# Answer
> 1 votes
First you create your two text formats (if not already present).

Then you can use the wysiwyg module (http://drupal.org/project/wysiwyg) to display an editor for the Full HTML text format (on /admin/config/content/wysiwyg). wysiwyg will only display editors that you have set up properly (usually by placing a third party library in sites/all/libraries)

You can limit use of the text formats via the permission settings.

---
Tags: input-formats
---


title: Remove pager from frontpage

text:
# Question
Title: Remove pager from frontpage
On the frontpage of my drupal site I have set up multiple blocks that display content from different views however, in the Content block region my news block is showing a pager that I am unable to remove.

In the news block I have configured the Pager settings to display a specified number of items and to use a more link that says view all. But the settings will not work in the content block region.

I have also tried to configure the frontpage with similar Pager settings and still no luck.

**System Information:**

* Theme: Bartik 7.12

# Answer
> 3 votes
I figured out what I was doing wrong. It had to do with the defaults of the page view path.

In the Front Page View I changed the page settings path to /home and went into **Configuration \>\> Site information** and scrolled down to the Front Page settings.

I set the default front page url to home and the pager was removed as per my configuration of the frontpage Page pager settings.

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


title: Adding geo location content to node

text:
# Question
Title: Adding geo location content to node
I'm looking for a maintained module that allows to add a geo location to a node of a custom content type. I am looking for something that has integration with Google Map API so that it's possible to query the location using an address, ZIP, or name.

# Answer
> 2 votes
If you are not a fan of Location and Gmap you can try out Gmaps or Open Layers. I am personally not a fan of the Location module and find it bloated and unintuitive. Open Layers has a number of modules that extend it's functionality. Plus it was developed by Development Seed so you know it's good.

# Answer
> 3 votes
If your are using drupal 7, then my favorite option is openlayers with address field and geofield.

The advantage of openlayers is that you are not tight to one particular map provider, but you can switch just by changing your options.

You can set geofield to take the value of the address field, geocode it and store the lon/lat value of the address. You can then draw the locations on the map. The geofield works with google or yahoo for geocoding.

---
Tags: 7, location
---


# Question
Title: CPN: Replacing tokens in physical css/js files
Hi I have some css / js attached to a box with Code Per Node. CPN creates physical files for the code. In `hook_preprocess_node` I can see the CPN output, for example:

```
$vars['cpn']['css'] = token_replace($vars['cpn']['css']);
$vars['cpn']['js'] = token_replace($vars['cpn']['js']);

```

This successfully replaces the tokens in memory but the physical file is loaded up in the header and so the tokens aren't replaced in there and cause an error. Any ideas?

Thanks

# Answer
Both `drupal_add_js` and `drupal_add_css` have an option to add code "inline". You can try his in a `template_preprocess_node`:

```
function mytheme_proprocess_node (&$variables)
{
  drupal_add_js($variables['cpn']['js'], 'inline');
  drupal_add_css($variables['cpn']['css'], 'inline');
}

```

If you do this in a theme, then the CPN hook should have already been fired. If you do it from a module, you may need to play with the module weights to get yours to follow.
> 1 votes

# Answer
Ok at the time of posting this there is no clean solution. You could pass all the cpn code inline but it isn't as easy as `$vars['cpn']['js']` because this is only the CPN for the node and the CPN for any blocks/boxes on the page is elsewhere. This could get messy and you would have to intercept any CPN js/css that would have normally been added to the page in `hook_js_alter` by removing anything coming from the custom cpn path - messy.

For now (not advised) you can edit the CPNs .module:

* Find `function cpn_save_file($data, $filename)` and add: `if(function_exists('token_replace') $data = token_replace($data);`
> 0 votes

---
Tags: files, tokens, blocks
---


title: Best module for facebook Opengraph

text:
# Question
Title: Best module for facebook Opengraph
I want to create an alumni association website. I want users to be able to sign up/login via facebook/linked in. Their details should be fetch from their social network profile. Are there any modules suitable for this criteria.

# Answer
> 2 votes
My favorite option for facebook is the Fboauth. There are other solutions as well like Drupal for Facebook and Facebook Connect.

Drupal for Facebook is intended for building Facebook apps. The Facebook connect functionality is just one of the features. While I was using the 6.x version I encountered many bugs, most were related to the constant api changes from facebook engineers. Have not used Facebook Connect. Fboauth however looks simple and easily extendable. It was a simple task to import data from the fb profile into the drupal site.

This is a nice post about the subject: http://grasmash.com/article/connecting-facebook-drupal-easy-way

---
Tags: social-network
---


# Question
Title: How can I create Folder like Structure with n Key Value Pairs?
I'm new to Drupal.

I'm trying to build the following structure

```
--Root
  --Cars
    --Luxury Car Campaigns (my "Folder")
      -Bentley CampaignInformation (1-n Key Value Pairs of different Types)
      -Lamgorgini CampaignInformation (1-n Key Value Pairs of different Types)
    --Japanese Car Campaigns (my "Folder")
      -Toyota Yaris CampaignInformation (1-n Key Value Pairs of different Types)
      -Corolla Verso CampaignInformation (1-n Key Value Pairs of different Types)

```

Note: A "Folder" is marked with a double-"--" and a key-value-list is marked with a single "-" (we call it internaly "Project"; but it is basically a named collection of key-value attributes/fields).

Every field can be of any type (Double, Data, Text and so on).

Every folder may contain unlimited subfolders or "Projects". (Must not be enforced by "Constraint")

Now the tricky Part (or not?): Users can create Folders at any time. Users can create "Projects" in any Folder. Users can add any type of key-value pair to any Project.

Please give me a hint. Can this be done with Drupal? Do i have to dive into writing custom Modules?

I know a lot of Questions. Thanks in advance.

# Answer
> 0 votes
If I get you right, this structure is a property of a campain. I'd create a hierarchical vocabulary and use it as a field in a custom content type create for the campains.

# Answer
> 0 votes
If its just hierarchial text/numbers/whatever content you want under "folders" you could try the built-in Book module. And then re-theme its display to have "parent" pages appear as folders and child-pages be your value fields (or pages). The nice thing you get here is some pre-built templates for "folder" indexes at every depth of the folder-tree.

Also the built-in book module supports HTML export and is pluggable so you can write your own custom `book_export_xml()` function, see: book.pages.inc book\_export($type, $nid)

Be aware drupal (book) pages nest at most 8 levels deep I believe by default -- I think there are work-arounds for this in the DB to go deeper (perhaps unlimited).

Or, you allow each user to have their own Taxonomy in drupal and try to use like Field Collection to allow users to create many values under a single term in the vocabulary.

Taxonomy sounds like it might meet your needs -- but you would likely have to make custom code something to allow users to create X number of taxonomies only they can see and manipulate.

Just fyi -- there is always a "maximum" in any dataset you have hardware constraints (RAM and harddisk) and can only store so much and still be responsive for the enduser. So be realistic and set yourself a max value, say 999 values per Key ....

Drupal can probably do what you want but it will take a fair amount of research.

---
Tags: taxonomy-terms
---


# Question
Title: Views - create relationship on relationship?
I'm confused with Views' query altering and adding joins. Need help (or at least a comprehensible documentation with code samples, because I've never found one).

Here is what I'm trying to do: I have 2 node types, Writers and Books. I use taxonomy to group Books by Writers. I've created a field in my taxonomy terms that references respective Writer articles. It looks like this:

* Books by Writers (dictionary)
    + Books by Isaac Asimov (taxonomy term, WriterId = 1 - references Isaac Asimov node)
        - I, Robot (Book node)
    + Books by Harry Harrison (taxonomy term, WriterId = 2 - references Harry Harrison node)
        - West of Eden (Book node)

Now I'm trying to build a view that looks like this:

* Isaac Asimov (Writer node title)
    + I, Robot (Book node title)
* Harry Harrison (Writer node title)
    + West of Eden (Book node title)

All in all, I need something like Book Nodes join Taxonomy Terms join Writer Nodes. In Views UI I'm able to display Book titles and add a relation to Taxonomy so that I can display all Taxonomy term fields. It looks like this:

* 1 (WriterId from taxonomy term)
    + I, Robot
* 2 (WriterId from taxonomy term)
    + West of Eden

How do I join Taxonomy and Writers to get access to Writer node titles?

# Answer
> 2 votes
As I understand you don't really need taxonomy here. Instead you can reference Book node to Writer node directly.
Of course, you can solve the problem without modifying your current structure. I will show how to create such View using Entity reference as referencing field. I recommend this module for creating references in Drupal 7 as it is powerful and stable.

1. First, create new View for Books content type:
2. Add relationship to taxonomy term:
3. Now you can add one more relationship to Writers nodes. Here Entity reference comes into play:
4. Now you can output all you want from Book node, from relative taxonomy term or from relative to that term Writer node. Just select appropriate relationship to use:
Here I added title from Writer node and excluded it from display.
You may want to group output by writer and it can be done in Format settings:

If you didn't use unnecessary dictionary, you would not need the second step.

About a year ago I started with NodeOne series Taming the Beast: Learn Views with NodeOne and Using the Reference modules by Johan Falk and I hope this information will help you too.

---

*Done with love to Isaac Asimov.*

---
Tags: 7, views
---


# Question
Title: Filter to only nodes with an image in an imagefield in Views 3
In my view, I want to include/exclude nodes that do not have an image in a specific field with exposed filter. The field allows an unlimited number of images. I don't care about the exact quantity, just that there are more than 0. How do I create this filter?

# Answer
> 0 votes
'Is not empty' is an option for the operator of filters. Did you try that?

So you can add a filter to your view, and just select that as your operator. Here's a screenshot to help:

---
Tags: 7, views
---