title: drupal_render() and drupal_get_form()

text:
# Question
Title: drupal_render() and drupal_get_form()
In the following snippet, the form returned has only the hidden values. No name, email, or comment.

```
require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';
$elements = drupal_get_form(array('contact_site_form'));
$form = drupal_render($elements);

```

Can anyone say why `$form` is not returning an HTML form?

# Answer
> 4 votes
```
drupal_get_form('contact_site_form');

```

---
Tags: 7, forms
---


title: Splash page for mobile website

text:
# Question
Title: Splash page for mobile website
I am working on a mobile website and I need to have a splash page for 3 sec displayed when the client access the website for the first time. Is there any plugin I can use or what solution can I use.

Thanks

# Answer
> 1 votes
Put a meta refresh tag in the header of your mobile splash page template:

```
<meta http-equiv="refresh" content="3;url=http://WHEREYOUREALLYWANTTOGO">

```

This will display the splash page for 3 seconds before moving on to the page you want them to see next.

---
Tags: 6, theming
---


# Question
Title: "Cannot declare self-referencing constant database.inc line 2101"
Suddenly, I got this error when I was configuring rules; the entire Drupal site is not accessible, not even update.php.

> Fatal error: Cannot declare self-referencing constant '' in I:\My Documents\web\xampp\htdocs\mysite\includes\database\database.inc on line 2101

The last thing I remember was configuring rules with custom PHP.

# Answer
> 3 votes
I suddenly got this same error on a Windows workstation.

It does not have anything to do with the content of the database (including cache); it occurs before it even connects to the database.

The only fix that worked for me was restarting apache.

### Notes

1. The character within quotes is "EOT" ("end of transmission"), which looks empty in the error message.
2. The line 2101 in database.inc is the start of the DatabaseStatementBase class.

---
Tags: 7, rules
---


# Question
Title: Auto pulling an image from a post in Views
I'm creating a custom view and I want to create thumbnails for the posts.

The problem is there is hundreds of posts and they all have 1-2 maybe 3 images in them. I want to pull the first image in the post and use it as a "post thumbnail" in a view.

Is this possible?

Thanks for any tips.

# Answer
Yes select the cck field in the fields of the view and then in its options select number of images to display to one. This should do the job.
> 1 votes

# Answer
Umm... are you saying that you have a content type that has html in it with several images along with text and you want to grab the img out of that content and display a thumbnail of it? Or, do you have a structured content type with image fields in it?

From your followup comment, it's html with images.

So..........

What you will have to do is a bit messy, but, if you look at the views create form, there is a Style Settings area with Theme Information. If you look in there, you can see what template files views uses to display your view.

You will have to find the template for the row of your view and edit that template.

In there, you will have to write some php code that looks through the field that contains your html, looking for the first img tag, grab it and output it, themed appropriately with css and all.

While complex, quite easily doable.

In the spirit of dull ax coding, this does the hacking:

```
$html='This is some random html with a [img src="/YOURIMAGEPATH" title="my image"] in it here and another one here [img src="/lrfmages/saloon320x50.jpg"]';

$content='<div>This is my html: ' . $html . '</div>';

$img=explode('<img ',$html);
$img=explode('>',$img[1]);

$content.='<div>Guts of first img tag: ' . $img[0] . '</div>';

$img=explode('src=',$img[0]);
$img=explode(' ', $img[1]);

$content.='<div>Guts of my src= attr: ' . $img[0] . '</div>';

$content.='<div>Therefore, my first image is <img src=' . $img[0] . '></div>';

return $content;

```

Perhaps not obviously, I used \[img\] above just so it wouldn't try to display an image in this form, change that to the appropriate less than IMG greater than in your code lol. And I wouldn't overload variables like I did above in production, I just wasn't feeling creative in names. And also, I am sure there is one regular expression out there that could do all of this, but this "shows the math" at least of showing how to split it up. Or so I hope. This worked here :)

Gack...looking at it, my quick code above assumes a space after the src= attribute, so it would fail if your image is set up as \[img src="foo"\] so you should craft this to your input specs. Fun eh? So you probably don't need to go that extra step if you don't mind having any other attributes that might be in with it, eg the title etc.
> 0 votes

---
Tags: views, 7, media
---


# Question
Title: When creating a content type programmatically, is there a way to add tuples (e.g. pairs) of fields?
In Drupal 7, I'd like to create a Person content type. A person may have multiple profiles - an administrator should be able to select which profile will be considered the primary one. So, that means that I need a tuple consisting of:

A textarea, for the profile text
A checkbox, indicating that this is the primary profile
A textbox, for naming this particular profile

I need functionality to behave like that of any of the lists: I can click "Add another Item", and a set of all three of these fields will appear.

I have a vague idea of how this can be executed, but it involves using the form API to add fields before the form renders each time, as well as the necessary AJAX behavior. This seems a bit overcomplicated, since this would also necessitate creating an additional DB table to hold these tacked-on fields.

Is there a relatively simple way of doing this solely through `hook_install()`?

# Answer
> 1 votes
The profile2 might fit your bill:

> Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)

---
Tags: entities, nodes
---


title: Contextual Filters Help - User Pages

text:
# Question
Title: Contextual Filters Help - User Pages
I am working with user pages and I have styled a user page with a custom .tpl and I am using a block to bring in the latest post from that user using views. I am having a problem sorting out the posts with contextual filters. I have set up the contextual filter to work if the URL was /user-name but because it is a users page the URL is /users/user-name and this is screwing up my filter. Any advice someone can give me?

# Answer
> 2 votes
I usually add a contextual filter for "user: uid", specify a default of "userid from the URL" and then set a validation criteria for "user" and "Allow both numeric UIDs and string usernames". That way you can use both the uid and the username.

You'll probably have your "last post block" show up on the profile edit page because it's at "user/%/edit". I changed my user profile pages to "member/USERNAME" using the pathauto module.

---
Tags: views
---


title: Bartik theme main menu

text:
# Question
Title: Bartik theme main menu
I am dabbling fresh with Drupal 7 and so far having little success with getting the Menu to behave the way I want it to. My CSS and PHP basics are strong, but understanding Drupal's system is in itself a huge challenge and hence my doubts.

For those acquainted with the Bartik theme, the main menu defaults itself in the header.

I am trying to create a floating/persistent menu that encapsulates the entire width of the website. But I am not sure where I need to go in and make the required changes.

One option I have is to remove the main menu from the Bartik header and then introduce the main menu block in the 'featured' region. Here the menu is rendering itself horizontally instead of vertically the way i want it to be.

Essentially the question is, How do I alter the main menu in the Bartik theme? Where do I need to get in and make changes.OH, and I have sub-themed it, just to let you know.

# Answer
> 3 votes
Take a look at the module Nice Menus or Superfish menus. Both offer a lot of flexiblity and control for managing menus. In both cases you will configure the module to provide some menu blocks and configure the blocks to attach them to your main menu. You will then put the Nice Menu (or Superfish) block where you want it and hide the main menu block. (I like superfish)

---
Tags: 7, navigation
---


# Question
Title: Wizard for generating a dynamic legal document
I have been tasked with investigating options for developing a Drupal module that would serve as a Wizard for helping users create a customized legal-agreement template based on a series of interview questions. Please note, I have had no experience with Drupal before last week, so I need specific answers that do not assume any knowledge on my part.

Essentially, this new tool would ask the user a series of questions on a variety of topics (and follow-up questions based on a decision tree), and when the interview is complete, the tool would produce a text document containing only those (pre-written) paragraphs relevant to the project. Alternatively, more experienced legal staff could bypass the interview and simply select the paragraphs desired by clicking on items in a list -- much like the way someone with tax experience can bypass the "Guided Tour" in TurboTax to select and manually complete the appropriate IRS forms. Other requirements: Our user interface for our interview must be intuitive to the average technophobe, and the user must be able to send the output into a MS-Word document (additional formats are a bonus). Our office is developing other web-based tools using Drupal 7; we have limited resources available for programming this tool, so simpler solutions are preferred.

Has anyone done anything like this, or know of tools/modules that we could adapt? What other advice do you have for us?

Thank you all in advance for your advice.

# Answer
For the longer list, you can add a content type (Structure -\> Content types) and add checkbox fields for each question, where the text of the question is the value displayed by the checkbox when it is selected (the "On" value). An alternative way would be to add a Checkbox field with multiple values. I suggest this because by default, just the value of the checkbox(es) is shown on the resulting content when you save and view it.

For the list of questions, it depends on how many questions we're talking about. A slightly tedious but straightforward way is to use the Rules module along with another content type that contains the questions.

This installs itself to Configuration -\> Workflow -\> Rules.

For each question, you add a triggered rule that checks the response and sets the value of the other content type (let's call it Template) to whatever it should be. You could probably do this one with one rule as well. In this case, I'd set the stored values in the database for the Questions type fields such that they match or somehow contain information about the names/values of the fields in the Template content type. It would basically be a mapping of sorts, and the rule could set the value of the Template based on this.

You may also need to store a reference to the Template content corresponding to the set of questions in the Questions type. The easiest way to do this is to install References and add a *Node reference* field to the Template content type. Then, you can have a rule that creates a new template and associates it with the Questions content when you save a new Questions content item, for example. The other rules would then have some saved content for which to set field values (otherwise, you'd wind up creating new Template content every time or something).

These are some thoughts on this. It's not the most elegant, but it might get you started or at least on the right track.
> 1 votes

# Answer
To address your question, I can only share my personal experience. I have a similar complex problem for a content rich website. I came to Drupal some programming experience including working with databases, but not in website applications. I could not find an out of the box system for developing my site. Drupal is very sophisticated and is probably the right tool for such a project, but it has a large learning curve and to do what you want will require knowledge of some of the more complex add-on modules and the ability to code in php for fancier requirements that are certain to pop up. Working daily for 4 months, I am just getting a handle on what is going on inside Drupal enough to plan the structure of the data and develop the content and User interface of the site. As you mentioned, generating the actual content is the simple part.

To do this project I would recommend that you have an experienced programming consultant that is knows how to structure the database keys (taxonomies in Drupal) and knows his/her way around Drupal programming.
> 0 votes

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


# Question
Title: D7: How do export content types, module settings, taxonomy terms, webforms and other nodes?
It seems D7 lacks an important feature for migrating data content types, module settings, taxonomy terms, webforms and other nodes.

I tried with Features modules but it seems it creates modules out of features and this is bad.

Where is Drupal CCK Content Copy Module for Drupal 7?

# Answer
It is **not** bad. It is preferable to store as much configuration as possible in code, so that it can be version-controlled and deployed easily elsewhere with Git etc.. Features makes this possible somewhat, but it is not yet feature-complete. Some work that is still on-going:

As there is no more CCK in Drupal 7, that content-copy feature is no longer available. We've moved onto Fields. If you want a quick way to get bundles exported without getting into Features, check out the Bundle copy module.
> 5 votes

---
Tags: importing-exporting
---


# Question
Title: How to import and merge existing site from svn to git?
I'm working with a site that has been using Subversion for version control and we'd like to swtich to using git instead. It seems like it would make the most sense to clone the Drupal project git respository from drupal.org, checkout the branch that represents the version closest to the existing site, create a new branch from that point and then somehow merge the existing svn repository into that branch. Is it possible to do that last step, to avoid losing the svn history?

For what it's worth, in one of the Pantheon demo screencasts they're doing something similar (around the 3 minute mark). It looks like they are starting with a backup of the site though, rather than importing a repository and its associated history.

Is there a better way to handle this scenario?

# Answer
> 1 votes
I don't see any advantages to being "in sync" with drupal git repo unless you're "chasing head."

I would just convert your current SVN repo to git. You can create a new branch that tracks drupal git and merge that branch in occasionally (if your directory structures match) or just download the final release packages and copy them into your directory and commit the changes.

---
Tags: importing-exporting, version-control
---


title: Using a newer JQuery version

text:
# Question
Title: Using a newer JQuery version
The Drupal 6 version of jQuery is too old (1.26). Could I delete, and replace it with a newer version?

# Answer
> 8 votes
Deleting the jQuery library used by Drupal 6 and replacing it with a newer version (especially if the new version is 1.3.x, or 1.4.x) is not a good idea because Drupal core JavaScript code (but also JavaScript code used by third-party modules) would stop working.

Some versions of jQuery comes with a compatibility file that allows to code though for the previous version of the library to work with the new version; sometimes, that single compatibility file is not enough for Drupal, as it is shown by the jQuery Update project, which replaces some of the JavaScript files used by Drupal, including ahah.js, tabledrag.js, and teaser.js.

As of 14 August 2011, the jQuery library used by the latest Drupal 6 version of jQuery Update is 1.3.2; jQuery 1.2.6 is the version used by the latest Drupal 5 version.

# Answer
> 11 votes
No, that would not be advisable; instead, use the jQuery Update module.

# Answer
> 3 votes
There's nothing wrong with using a newer version of jQuery alongside Drupal's core version of jQuery. The function noConflict() is made for running a jQuery library alongside another javascript library, even if it's just another version of jQuery (http://api.jquery.com/jQuery.noConflict/).

I wrote a post about using noConflict + your custom jQuery version and scripts here: http://drupal.org/node/1058168

# Answer
> 2 votes
For what it's worth:

* Drupal 5: jQuery 1.2.6
* Drupal 6: jQuery 1.3.2
* Drupal 7: jQuery 1.5.1 and jQuery UI 1.8.11

With the release of IE9 imminent, and jQuery 1.5.1 release was made to fix all bugs related to IE9, does it make sense to put this release into D7? Their changelog suggests many IE related bugs were fixed.

"jQuery now supports Internet Explorer 9 as a top level browser. All known bugs have been fixed and/or been reported to the IE team for resolution in the final release."

---
Tags: 6, javascript
---


title: Question on Site Structuring

text:
# Question
Title: Question on Site Structuring
In Drupal 7.x, is there a general rule on creating the page hierarchy? I'm porting over an old Joomla 1.x website to drupal, and the site index is pretty big with about 6 levels, and a lot of it resides on the main menu.

Would I create a static page (content), link it to the menu, and then create child static pages and link it to the submenu (as this is how I've started doing it) or is there a simpler way of doing this?

# Answer
Yes, if you want a fixed hierarchy, placing nodes in a menu structure is the way to do it.

That said, 6 levels is a lot, so I doubt if it's really the best way for your users to find the content they're looking for. You could consider using Views to create lists (maybe with filters) of content.
> 2 votes

# Answer
If your content is actually hierarchical, you can use Views tree and forget about the menu system altogether.
> 1 votes

# Answer
You can use Feeds and Feeds SQL to import the data automatically.
> 0 votes

---
Tags: routes
---


# Question
Title: Show data like tool tip when hovered over portion or regions on a custom map
I have a map and i want to create some regions in the map. When hovered on that region i need to show some content from database may be preloaded also. so which module should i use to create this task. when i hover should be able to show some click-able links to the user.

# Answer
I found these 3 links useful.

http://www.red-team-design.com/image-map-with-css3-jquery-tooltips http://www.workwithchoicecuts.com/methodology/revisiting-the-html-image-map/ http://www.workwithchoicecuts.com/demo/html-image-map-revisted/index.htm
> 0 votes

# Answer
What kind of map is it? An HTML imagemap (using and tags)? If so, you can use the EasyToolTip and MapHilight JavaScript libraries. They aren't connected to any Drupal modules, as far as I know.

EasyToolTip allows you to format the tooltips almost any way you want, and MapHilight allows you to highlight the section of a map that the mouse is hovering over.
> 0 votes

---
Tags: 7
---


# Question
Title: Real-time workflow scheduled transitions?
I have a simple workflow and am trying to figure out a way to get workflow scheduler to make node state changes in real time, at their scheduled time.

1. I set the state change on a node to occur at 09:00 from draft to live.
2. If cron runs before 09:00, the state does not change until the next time cron runs.
3. If the next time cron runs is not until 11:00AM, the state change doesn't occur until 11:00.

This is a problem since editors expect their content to go live *when they tell it to go live*. This does not seem like difficult functionality, but maybe I missing something basic. I understand that I can run cron more frequently, but it seems crazy that my cron schedule has to match the editor's publishing workflow, as in, "you should always have articles go live at 9am because that's when cron runs". What happens when editors want a node to go live outside of the normal cron schedule? It seems I missing a way for Drupal to "wake up" at this time and run cron to make the node live. Does anyone have a way to do this that I am overlooking? I find it hard to believe that news sites running in Drupal like economist.com or examiner.com don't have this type of real-time scheduling functionality. Thanks in advance.

# Answer
> 2 votes
You can use Elysia Cron to let the workflow cron hook run every minute, without sacrifing performance by having other cron hooks run that often.

See Multiple (and differents) crons?

# Answer
> 1 votes
I had this issue when I worked with media website, and the only way that you fixed it, is to increase the cron frequency. In my case it was every five minutes, but it means that your node can be live at 9:00 or 9:05 according the cron.

And in case if it wasn't enough, you already thought about other ideas to fixe, it, and one was to use an external service, like Google App Engine TaskQueue or another similar service in your own server.

Or if you want to do it live, you still can let all your node publish (so live) but you restrict the select (with views) with all node who has time equal or lower than actual. But, you gonna have the cache problem in that case also.

---
Tags: workflows, rules
---


# Question
Title: Use my existing jquery function in drupal 7
I have my function like this in jquery

```
$(document).ready(function(){

    // set the map-wrapper width and height to match the img size
    $('#map-wrapper').css({'width':$('#map-wrapper img').width(),
                      'height':$('#map-wrapper img').height()
    })

    for (i=0; i<$(".pin").length; i++)
    {
        // store initial tooltips contents within an array
        var tooltipContent = new Array();
        tooltipContent[i] = $(".pin").eq(i).html();

        // set tooltip direction type - up or down
        var tooltipDirection = 'tooltip-up';
        if ($(".pin").eq(i).hasClass('pin-down'))
        {
            tooltipDirection = 'tooltip-down';
        }

        // append the tooltip
        $("#map-wrapper").append("<div style='left:"+$(".pin").eq(i).data('xpos')+"px;top:"+$(".pin").eq(i).data('ypos')+"px' class='" + tooltipDirection +"'>\
                                            <div class='tooltip'>" + tooltipContent[i] + "</div>\
                                    </div>");
    }

    // show/hide the tooltip
    $('.tooltip-up, .tooltip-down').mouseenter(function(){
                $(this).children('.tooltip').fadeIn(100);
            }).mouseleave(function(){
                $(this).children('.tooltip').fadeOut(100);
            })
});

```

But i am unable to use it in Drupal 7 . So what changes do i need to make for it.

# Answer
> 6 votes
Your are missign two important things. First, in Drupal 7 jQuery is namespaced to avoid conflict with other JavaScript libraries. So you should either wrap your code in an anonymous function to assign the `jQuery` object to the `$` variable (ie. `(function($){...})(jQuery);`) or use `jQuery` instead of `$`.

Second, you shouldn't use `$(document).ready()` but add you code as a the attach function under the `Drupal.behaviors.yourModule` namespace. Behaviors are attached on the `document`object on load, but also to any new element added to the page by any well behaving scripts (the ones that call `Drupal.attachBehaviors()`). Finally, because behaviors could be attached several times to the same DOM tree, you should avoid processing the same element multiple times. This can easily be done with jQuery Once.

```
(function($){
  Drupal.behaviors.myFunkyModule = {
    attach: function(context, settings) {
      // Get the map wrapper element (anywhere in the document).
      var map_wrapper = $('#map-wrapper');
      //Set the map-wrapper width and height to match the img size only once.
      map_wrapper.once('my-funky-module').css({
        width: $('#map-wrapper img').width(),
        height: $('#map-wrapper img').height()
      })
      // Get the (un-processed) .pin elements, in the context (ie. DOM tree) our behavior is attached to.
      var pins = $(".pin", context).once('my-funky-module');
      // Process the pin elements (note: this could also be done using jQuery.each()).
      for (i=0; i<pins.length; i++) {
           var pin = pins.eq(i);
          // store initial tooltips contents within an array
          var tooltipContent = new Array();
          tooltipContent[i] = pin.html();

          // set tooltip direction type - up or down
          var tooltipDirection = 'tooltip-up';
          if (pin.hasClass('pin-down')) {
              tooltipDirection = 'tooltip-down';
          }

          // Append the tooltip elements to the #map_wrapper one.
          map_wrapper.append("<div style='left:"+pin.data('xpos')+"px;top:"+pin.data('ypos')+"px' class='" + tooltipDirection +"'><div class='tooltip'>" + tooltipContent[i] + "</div></div>");
      }

      // Add event listeners to show/hide the tooltip, again this only need to be done once.
      $('.tooltip-up, .tooltip-down').once('my-funky-module').mouseenter(function(){
        $(this).children('.tooltip').fadeIn(100);
      }).mouseleave(function(){
        $(this).children('.tooltip').fadeOut(100);
      });
    }
  }
})(jQuery);

```

# Answer
> 2 votes
Try wrapping the entire function into this:

```
(function($) {

  //.. your function here ..

}(jQuery));

```

then you would get:

```
(function($) {

  $(document).ready(function(){

      // set the map-wrapper width and height to match the img size
      $('#map-wrapper').css({'width':$('#map-wrapper img').width(),
                        'height':$('#map-wrapper img').height()
      })

      for (i=0; i<$(".pin").length; i++)
      {
          // store initial tooltips contents within an array
          var tooltipContent = new Array();
          tooltipContent[i] = $(".pin").eq(i).html();

          // set tooltip direction type - up or down
          var tooltipDirection = 'tooltip-up';
          if ($(".pin").eq(i).hasClass('pin-down'))
          {
              tooltipDirection = 'tooltip-down';
          }

          // append the tooltip
          $("#map-wrapper").append("<div style='left:"+$(".pin").eq(i).data('xpos')+"px;top:"+$(".pin").eq(i).data('ypos')+"px' class='" + tooltipDirection +"'>\
                                              <div class='tooltip'>" + tooltipContent[i] + "</div>\
                                      </div>");
      }

      // show/hide the tooltip
      $('.tooltip-up, .tooltip-down').mouseenter(function(){
                  $(this).children('.tooltip').fadeIn(100);
              }).mouseleave(function(){
                  $(this).children('.tooltip').fadeOut(100);
              })
  });

}(jQuery));

```

# Answer
> 1 votes
Try this:

```
(function($){

  // your code

})(jQuery);

```

Have you added the file with the drupal\_add\_js() function or have you added it to your template.info file?

---
Tags: 7, javascript
---


title: Facebook OpenID Selector

text:
# Question
Title: Facebook OpenID Selector
I work with the OpenID Selector; everything is OK, but nothing happens when I click on "Facebook."

I work with the Drupal for Facebook module; this works fine, but with the OpenID Selector just it's just select the facebook icon.
Another issue is when a user log in to my website and needs to log out; the user is still logged in with the service he used.

# Answer
From the libraries/openid-selector/README.txt:

> 1. how to plug-in facebook provider
> put the following code in providers\_large or providers\_small:

```
facebook = {
     name: 'Facebook',
     url: "javascript:facebook_click();"
}

```

> where facebook\_click is something like:

```
function facebook_click() {
      $('#<id of html fbconnect element>').click();
}

```

> the same mechanism also applies if you want to plug-in any oauth or xauth provider

So that is what the README says. I specifically had to do the following I'm using Drupal7.8 with openid-selector module 7.x-3.x (2011 May 07):

In modules/openid\_selector/openid\_selector\_fb.js: Replace the chunks that look like similar with the ones Ive posted.

```
providers_large.facebook = {
  name: 'Facebook',
  url: "javascript: $('.fb_button').click();"
};

```

and again for this chunk

```
Drupal.behaviors.openid_selector_fb = { attach: function (context) {
  $('.fb_user-login-button-wrapper').hide();
}}

```
> 2 votes

# Answer
I would suggest you to make use of the facebook Like button source code. http://developers.facebook.com/docs/reference/plugins/like/ use this link to get the source code and put them in your template file. I am not sure it may help you or not, but still this method fixed my problem once.
> 1 votes

---
Tags: authentication-authorization
---


# Question
Title: How do you validate against empty form fields in D7?
In D6, the method I used was to store the value of form fields into a variable and then setting an error message of the variable == null.

Is this still possible in D7, or is there a better way to handle this? The fields I'm trying to apply custom validation to are select lists so I imagine there must be a different technique.

# Answer
> 2 votes
I figured it out on my own: The process is the same as in Drupal 6. The arrays have just changed a bit. To use a custom validation with `hook_form_alter()` and a custom validation function, you would load your form\_state values as follows (example based on fields from profile2):

```
function example_validate($form, &$form_state) {
  // Store our field values to validate against.
  $fieldname = $form_state['values']['profile']['field_name']['und'][0]['value'];

  if ($fieldname == null) {
    form_set_error('profile][field_name', t('Error Message'));
  }
}

```

The actual value for our fields is now found in the `'und'` array. Since the `#parent` property of these profile fields is an array, use `'foo][foo2'` format to specify the element for which to show the validation error. See form\_set\_error().

---
Tags: forms
---


# Question
Title: How to count the number of posts by a author?
I have created a view with table settings. I would like to display the name of the author and the total number of posts that he has created. I have used relations to get the author name but I don't see any fields related to count the number of posts.

Any suggestions?

# Answer
> 6 votes
If you are using D7 I think you will have to enable `aggregation` for you view, and then set the `group by` for you field (`Content:nid` for example) to `Count`.

# Answer
> 0 votes
Which version of Views/Drupal are you using?

The User Stats module may work for what you need.

---
Tags: views
---


# Question
Title: Can I search for parent nodes from deep child nodes using Views?
I've a complicated hierarchy of nodes. Node A contains(by node reference) multiple B nodes, each B contains multiple C nodes and so on.

Using Views will it be possible to reach C from A or vice versa given even higher depth level?

I think this is independent of D6/D7 views but I'm on D6.

There will be thousands of such nodes. Each top level A is an organization and there are a 1000 of them now. Information about each employee or department will be held in File(aka file cabinet) which again is a node).

I want to give users facility to search information from one end to another.

Update: The parent to child relationship is one to many

# Answer
> 0 votes
You have a bunch of options. I am using noderelationships and thinking of pairing it with reverse\_node\_reference.

I'd look into these modules.

D6: http://drupal.org/project/noderelationships

D6: http://drupal.org/project/reverse\_node\_reference (See http://drupal.org/node/798786 for some good insight)

D6, D7: http://drupal.org/project/cnr

D6: http://drupal.org/project/nodereferrer

D6: http://drupal.org/project/backreference

D6: http://drupal.org/project/partners

D7: http://drupal.org/project/references

# Answer
> 1 votes
You can probably do it with the Corresponding Node References module. Otherwise you can't do reverse references at all. You'll use relationships, of course, to go both ways.

---
Tags: views, nodes
---


title: Localizable text in custom layout?

text:
# Question
Title: Localizable text in custom layout?
I'm customizing Display Suite-suggested tpl by adding "Jump to top" links at the bottom of each teaser and I want to properly localize the link text.

Now I am unclear as per the usability of the Variable module (that had to be installed along with i18n). Can I add my own variable (say, jump\_to\_top\_link) somewhere in the Variable admin panel, without writing my own module? Or is Variable meant only as an API for modules?

I don't want to learn module development now, but I want my custom text to be scalable and easily manageable from one place, instead of hard-coding strings and ifs.

Would anyone be willing to shed light on how to approach the problem?

Regards, Artur

# Answer
> 1 votes
You can set the translations for each specified language in the strings settings part of the internationalization module: /admin/config/regional/i18n\_translation

To show it in a template file you simply use the t() function to wrap your text - which translates text for you and automatically adds new text defined in the t() function to the strings page.

See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

If you are hardcoding links with your text you can use l(), so if you have say a text link and want the text to be translated you would use l() and in it define your text using t() - something like this: http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

See http://api.drupal.org/api/drupal/includes--common.inc/function/l/7 for its usage.

---
Tags: i18n-l10n
---


title: Where is links__node__node() defined?

text:
# Question
Title: Where is links__node__node() defined?
I'm trying to figure out how I can alter the theme for read more links. This is what goes on inside the node.module ~ line 1380.

```
$node->content['links']['node'] = array(
  '#theme' => 'links__node__node',
  '#links' => $links,
  '#attributes' => array('class' => array('links', 'inline')),
);

```

I know where are several ways to remove the read more links and add your own, but I just want to know where that theme function is stored and how I can override it like it can be done with fields using `theme_field()`.

# Answer
The function defined in include/theme.inc is theme\_links($variables); in your theme define `yourtheme_links($variables)`.
> 1 votes

# Answer
The "`links__node__node`" theme function is not defined from any Drupal module. If a module defines a theme function matching that name, then Drupal will use it; otherwise, the function that is going to be used is theme\_links().

In your theme, you can define both the theme functions. The difference is that `theme_links()` is generally used, while the other theme function is used just in a specific case.

```
function themename_links__node__node(&$variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  // …
}

```

```
function themename_links(&$variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  $heading = $variables['heading'];
  // …
}

```
> 3 votes

---
Tags: theming, navigation
---


# Question
Title: What is the proper syntax to call the theme function for a node, passing an argument?
I'm writing a Drupal 7 application that has many content types. Each of these content types has a custom template for display. For instance, I have node--event.tpl.php, node--person.tpl.php, node--feedback.tpl.php, and so on.

I'd like to be able to manually call a theme function on a node that should have an overriding template. i.e. something like the following:

```
<?php print theme('node', array('node' => $node)); ?>

```

The reason for this is that I've written a module called Content Inclusion which allows pieces of content to be manually included within one another. I'm trying to have this line of code in my node.tpl.php file to automatically display the included node along with the parent node.

I appreciate any and all suggestions, but I would be more interested in learning about ways to make this work - this module has some very specific requirements that existing modules were not able to address. Thanks.

# Answer
> 4 votes
You should use the `node_view` function for that, which attaches fields to the node and creates a build array, which when rendered will use the node theme function that you try to use directly.

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


# Question
Title: Where is the file selection widget in Drupal code?
If a content type has an image field then when the user creates new content, he is present with an image section on the form with a widget to "Browse" for a file. Clicking it provides a pop-up window standard dialog box for selecting a file. I would like to examine how this works to use it in a custom module, but cannot locate the code in the core modules.

# Answer
The dialog box is a feature of your browser. The server sends HTML code looking something like

```
<input type="file">

```

Most browsers render this by providing a text input field and a *Browse* button.
> 1 votes

# Answer
The code to generate a field upload form element is in `theme_file()`. The code is very simple because all it does is to output an HTML file select form element. As explained in other answers, the files browsing dialog is provided by the web browser and, most of the time, re-uses the operating system native one.
> 2 votes

# Answer
You are confusing client side and server side. The code you are seeking is internal to the browser (the client); it is not within Drupal (the server).
> 0 votes

---
Tags: 7
---


# Question
Title: How do I incorporate a browser file search into a Drupal form?
This question extends a previous one. The previous answer stated that the pop-up window to search the user's computer for a file to upload is called using . I am not certain how to make the call from within the form\_submit function and have searched the core code for an example without success. I know that add content has a widget to add an image file, but I cannot find the code generating it. I even did a file search for the word "Browse" which is the title of the button without finding a single file.

Does anyone have an example of how I would direct a call to a browser function from within the Drupal form? OR Does anyone know where the add content form widget for adding a file is at?

# Answer
> 1 votes
To output a file select form element in a Drupal form, you simply add a `file` or `managed file` element.

```
$form['upload'] = array(
    '#type' => 'file',
    '#title' => t('Choose a file')
  );
)

```

# Answer
> 0 votes
again, you are confusing client and server. the code that generates the popup is within the browser (client). it is not within drupal (server). all drupal does is "send" an html request that is interpreted within the browser which then presents the content to the user. the browser creates whatever is needed, whether it be **this is bold text** by sending a "less than" b "greater than" this is bold text "less than" "slash" b "greater than" or something more complicated like a form element asking for a file.

---
Tags: 7, forms, files
---


# Question
Title: How can I print the views title in node.tpl.php?
I could print the view with this code in node.tpl.php.

```
<?php
$view = views_get_view('view_name');
print $view->execute_display('view_display_name', $args);
?>

```

How can I print the views title ?

# Answer
```
print $view->display['view_display_name']->display_options['title'];

```
> 1 votes

---
Tags: views, theming
---


# Question
Title: Rules Looping for Multiple User References
I have a Rule which checks to see if a "Reviewer" CCK User reference field has been changed. If it has been, it loads the referenced user and add the "Reviewer" role. This works perfectly however it only works for the first value in the field, so adding multiple reviewers becomes a problem.

I can see in the "load a referenced user" action that is says "Note that if the field has multiple values, only the first user will be loaded." So I assume this has come up before...

Is there any way around this for Rules 1.x on Drupal 6? I need to Loop this for each set value in the field array but I cant find the best way to do so...

# Answer
> 1 votes
You could write you're own condition. See http://drupal.org/node/298486.

---
Tags: 6, entities, rules, users
---


# Question
Title: Why I'm having fatal error when adding PHP code to my text format?
So I set the text format to "*PHP code*" and add the following code:

```
<?php
function f($x) { return $x; }
?>

```

When I hit Preview, the page dies with `Fatal error: Cannot redeclare f()`. I have tried this on two separate Drupal 7 sites, one more or less brand new, with the same result.

Is there a step I'm missing to use D7's PHP filter?

# Answer
> 3 votes
```
<?php
  if (!function_exists('f')) {
    function f($x) { return $x; }
  }
?>

```

"should" make everyone happy :-) If not, maybe include\_once(FILE.php);

# Answer
> 5 votes
I just tracked this down.

What happens is that previewing a node will invoke both the *teaser display* and *full node display*, and both of those invoke the PHP code.

My solution was to set the teaser to hidden for the content type (at Structure \> Content Types \> \[your node type\] \> Manage Fields \> Teaser). However, I didn't want to do this for default types like Basic Page, so I created a new type "PHP Tests" and only made the change there.

So I think this shows how PHP in nodes can get ugly, but for people like me who basically want to eval code in the Drupal environment without making a module sometimes, the above is an okay solution.

# Answer
> 4 votes
Nodes are meant for content, not for custom code. To me, your question looks like "I want to drive my car in reverse, but the steering wheel is on the wrong side. Please help my fix my car." I'd rather teach you how to drive forward :-)

The "Drupal way" to run your own code in your site is to create a custom module. That may sound difficult, but it's not.

First, you create a folder in sites/all/modules. Use the name of your module as folder name, I will use 'mymodule' as example.

Second, you create two files in that folder, called 'mymodule.info' and 'mymodule.module'. In mymodule.info, you enter:

```
name = My module
description = This is an awesome module.
core = 7.x

```

Adjust the name and description as you like. See the documentation to learn more about .info files.

Third, enter the following in mymodule.module:

```
<?php
/**
 * Implement hook_module.
 */
function mymodule_menu() {
  $items['my-module'] = array(
    'title' => 'RSS feed',
    'page callback' => '_mymodule_run_import',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function _mymodule_run_import() {
  // Place your custom code here.
}

```

This code registers the 'my-module' path using hook\_menu, which means that Drupal now "knows" that when you navigate to http://example.com/my-module, it needs to run the mymodule\_run\_import() function.

If you decide to use another name instead of 'mymodule', make sure you replace all occurrences of 'mymodule' (both in file/filder names and in the code) with the new name.

As a final step, you need to enable your module.

I hope that helps.

---
Tags: 7, input-formats
---


title: create a node outside of drupal

text:
# Question
Title: create a node outside of drupal
I have a situation where I need to create a node that is of a custom content type outside of drupal.

Is there anything involved besides inserting an entry into the node table and data into the content type table?

# Answer
> 3 votes
Unless you known exactly what you are doing, don't try to integrate with Drupal at the database level.

Drupal database schema is *dynamic*. Tables to store nodes information are added and modified when you add fields or change theirs settings. So your database query will need to be checked for every changes. This could easily become a maintenance nightmare.

Any module can, an many do, add custom behaviors on node insertions and updates through Drupal hooks system. Inserting content in the database without using Drupal's API would bypass these added behavior and potentially create inconsistent data.

If you must really do it outside Drupal, you can either bootstrap Drupal in your PHP *standalone* script to be able to use its API or use the Services module to provides a REST API for node CRUD operations.

To bootstrap Drupal in your PHP script, use the following code. Note that most of Drupal's code expect the current dir to be Drupal's one. Drupal also register its own session handler that may conflicts with yours.

```
chdir("/path/to/drupal");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

# Answer
> 0 votes
Maybe you can try to use the feeds module (http://drupal.org/project/feeds). That way you can have data in external databases, export them to csv, .... and then use feeds to import them. The module has a nice feature of mapping custom fields (eg. defined in your export csv file) to fields available in Drupal. If you use this module, you don't need to think about saving the data yourself to the correct tables,it handles that stuff for you.

# Answer
> 0 votes
If your code is run as CLI you could write it as a drush command. This way all the bootstraping is done for you for free.

Once you have you're drush command you can use it in almost any shell script.

The drush module has a good example on how to write your own commands.

---
Tags: 7, nodes
---


# Question
Title: A way to choose a block title's format (HTML tag)
What I would like to do is be able to choose what type of Headline HTML element (h2, h3, etc) to use for each block's title. The only way I can find to change a block's Title is in block.tpl.php. But this forces every block on the site to all have the same Headline.

I've Google'd and searched Drupal.org for a module or manual way to do this but have not found one. Does anyone know of a module that does this?

# Answer
> 1 votes
I know you are asking about D7, but you are missing a key point about templates. I'd take a gander at http://drupal.org/node/104319 which talks in great detail how D6 does it so you can how it can look at different block templates and then think about whether you need to create a module that has a configuration page for its blocks like what you have above or whether block location is enough.

---
Tags: 7, blocks
---


title: Validate an ubercart checkout pane?

text:
# Question
Title: Validate an ubercart checkout pane?
I'm using the uc\_ddate module.

How would one hook into the checkout pane to cause it to force it to validate and make the delivery date option required?

# Answer
Would that checkout pane still be captured by hook\_alter\_form()? If so you could add #required to the field there. Let me have a quick try and I'll get back to you.

EDIT: OK, this worked for me:

```
function tools_utilities_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'uc_cart_checkout_form') {
    // Make delivery date required
   $form['panes']['ddate']['ddate']['#required'] = true;
 }
}

```

Create your own module (mine is called tools\_utilities in this example) and implement the above and you should be good to go :)
> 3 votes

---
Tags: ubercart
---


# Question
Title: Ubercart 2.x drupal 6 combo attributes price
Is it possible to set a different price for each combination of attributes in Drupal? For example when A and C, the price is $10; when I select B and C, the price is $12; when I select B and D, the price is $13. I see http://drupal.org/project/uc\_custom\_price; it works, but I have too much combination for each product. There is a module, http://www.ubercart.org/project/attr\_combo\_price, but it is for Drupal 5.

Are there any other solutions?

# Answer
Would Ubercart Attribute Tokens help you out here?
> 1 votes

---
Tags: ubercart
---


# Question
Title: How to change a CCK value from a custom module
I would like to change a CCK value from an action triggered by the user. I built a custom form with a submit button that leads to a hook\_validate(). I would like to update a field value from my function. I know the nid and the field\_name, I can't find how to do it using CCK API.

Any ideas ?

# Answer
With the nid stored in $nid and changing FIELD\_NAME to your specific field name, once you have your new field info back from your form nicely stored in $new\_info all you need to do is:

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

$node->FIELD_NAME[0]['value']=$new_info;

node_save($node);

```

This is assuming a couple things, one that it's the first value in a field, the \[0\] up there, and that the field is one that has a \['value'\] component. Other types of fields have different things here, the most common that immediately comes to mind is \['nid'\] if it's a reference field.
> 2 votes

---
Tags: entities
---


title: Why is url() outputting two '//'s?

text:
# Question
Title: Why is url() outputting two '//'s?
```
  $form_state['redirect'] = url('node/add/media/' . $form_state['nid']);

```

When I get redirected it ends up at "http://mysite.net//node/add/media/772"

Any ideas?

# Answer
I might be talking out my you know what, but just try:

```
$form_state['redirect'] = 'node/add/media/' . $form_state['nid'];

```
> 2 votes

---
Tags: 6, uri, redirection
---


# Question
Title: How can I trim the display of text and expand with "more" link?
On my user profile page I have a "about me" text field that can get pretty long. I would like to only show about 200 characters of text with a "more" link. When you click more it would show the rest of the text, ideally on the same page.

# Answer
Look, up in the sky. It's a bird. It's a plane. It's...... sorry. This is a job for jQuery. A quick google of "jquery more less toggle" (without the quotes lol) will show lots of examples.
> 2 votes

---
Tags: 7
---


title: Custom taxonomy page that lists content

text:
# Question
Title: Custom taxonomy page that lists content
In Drupal 7, I'm trying to create a page that shows all terms in a specific taxonomy, along with node content that uses the taxonomoy.

What I'm hoping to do is create what's essentially a grid of views, where each term in the taxonomy displays: an image associated with the taxonomy term (the image field was added to this particular taxonomy), and then below it a list of nodes tagged with that term, ideally with each list having its own mini pager (although a complete listing or a partial listing with a "more" link would also work if a pager is not achievable).

I'd also like to do this without Panels, since I'm not using it anywhere else on the site.

Can someone point me in the right direction as to how I should approach this?

# Answer
> 3 votes
The quickest way I know of is by using Views.
I would create a special "content type" with a special **image field**, a **text field** to describe the meaning of the Tag, and a **Term Reference field** to include the applicable tag later. Then I would enter one image + text for each existing tag and assign it to the tag itself. Later with the help of views I would customize display-views like the one you have mentioned which would take just a few minutes to do.

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


# Question
Title: Proportional scaling to max width and height with ImageCache
I am not sure if this really is this difficult, or if I can't come up with the right search terms, but an ImageCache use case has me stumped right now.

I have a theme where I need to proportionally scale images to a max height and width (ie, a bounding box), and if possible center the image on a colored background.

For example, lets say I have a 1024x768 image and max size is 500x400. I need ImageCache to make a 500x375 image. The action would need to work for arbitrary image sizes, as the input varies widely.

Non-proportional scaling and/or cropping is not an option due to usage rights.

What is the best option here? I have gone through module that add additional ImageCache actions, but did not see any that did this. I suspect I could use ImageMagick Raw Effect but I would rather not rely on a particular toolkit, as I may need a portable solution.

# Answer
Add two scale actions to a preset. On the first one, set the width to 500, and in the second, set the height to 400. Since they don't by default up-scale, that should bound you in your box.
> 1 votes

---
Tags: 6, media
---


# Question
Title: How do I reference (what is the syntax I have to use) to get the data of my Profile2 custom fields?
I have used the Profile2 module (D7) and created some custom fields for my users. One of those fields (for example) is "field\_company" with the label "Company."

Now I am using a computed field (*Company*) on a content type (*Games*). When user creates a *Game*, I want my computed field *Company* to be computed/populated automatically, based on the "field\_company" field I have set in my profile2.

I am trying to find how to get that information. This is as far I got, so far, but it doesn't work.

```
$entity_field[0]['value'] = "";
$name=$profile2->field_onoma[LANGUAGE_NONE][0]['value'];
$entity_field[0]['value'] = $name;

```

# Answer
> 1 votes
You should use the field\_view\_field() function. Have a look at the follwing page for more information: http://coder1.com/articles/printing-or-rendering-node-field-or-profile2-field-drupal-7

# Answer
> 0 votes
```
drupal_set_message('<pre>' . print_r($profile2,true) . '</pre>');

```

or changing $profile2 to whatever variable is in your code you want described is a great way of seeing what's going on...

---
Tags: entities, users
---


# Question
Title: Any suggestions for Taxonomy scaling and performance with 1073 terms?
I manage a website where the owner categorizes everything via taxonomy. However, he's extremely detailed when it comes to categorizing things. He has 1073 taxonomy terms, about 1000 of which are in one single vocabulary. The node edit screen takes 10-15 seconds to load!

I've told him he needs to consolidate but he's not going to.

Does anybody have any advice for performance tuning? Changing to the ajax autocomplete control isn't an option because he needs to be able to see the hierarchy.

# Answer
> 3 votes
1000 terms is not so bad, really. I am inclined to believe the number of terms in your vocabulary is not what has the most impact on response time, as MySQL can handle much larger datasets out of the box. One factor to consider is the hierarchy of your taxonomy, or the number of levels it has. A vocabulary with 3-level-deep hierarchy will be much slower than a vocabulary that is implemented as flat hierarchy.

Good-luck

# Answer
> 0 votes
If you have 1000 taxonomy items in a select list, that would cause slowness on node add/edit

If you change it to free tagging this problem should go away, although if your client really wants to pick from a drop down list, that might not work for them.

I run several sites, some have 10k terms in the tags vocabulary but since it's not in a drop down it doesn't cause any problems at all.

---
Tags: taxonomy-terms, performance
---


# Question
Title: Dynamic "My Account" text in navigation menu
How would I go about modifying the "My account" text in the navigation menu, to link the title to a title callback?

My goal is to have "My account" say "My premium account," "My guest account," and so on when an applicable user is logged in. For most menu items, this would be easy to do with hook\_menu\_alter and a title callback.

But, hook\_menu\_alter doesn't seem to effect this menu item at all. Any ideas?

# Answer
> 1 votes
Drupal caches menu items, so if you're using hook\_menu\_alter you'll need to clear the menu cache to make your changes apparent. For your requirements, hook\_menu\_alter is no good anyway, as the menu has become dynamic!

My suggestion would be to use Menu Per Role. Create one menu that has each of your required menu titles in as seperate menu items (ie one menu containing three menu items; one for each type of account) and then restrict the visibility of those menu items to users with particular roles.

eg

* My Account Links
    + My Account - only visible to standard users
    + My Guest Account - only visible to guest account holders
    + My Premium account - only visible to premium account holders

When set up correctly, this will only display one link per user (although when logged in as user 1 you will see all links).

# Answer
> 0 votes
does each of them map to a user role? If so you would setup menu items for each of them and then use the "RESTRICT ITEM VISIBILITY" menu setting.

# Answer
> 0 votes
This can be done for instance within your theme, as the block will be shown for all users I assume. You'd create a function like so:

```
YOURTHEME_preprocess_block(&$variables) {
  global $user;
  if($variables['block']->delta == 'account' ) {
    $roles = array_values($user->roles);
    if (in_array('guest_role', $roles)) {
      $variables['block']->subject = 'My Guest Account';
    }
    if (in_array('premium_role', $roles)) {
      $variables['block']->subject = 'My Premium Account';
    }
    if (in_array('basic_role', $roles)) {
      $variables['block']->subject = 'My Account';
    }
  }
}

```

---
Tags: 6, navigation
---


# Question
Title: Render add node form within module output
I have a content type called “osago”. And I have a module that outputs some things.

How can I output the *create this content type* form within this module?

# Answer
> 2 votes
You will have to use `drupal_render()` on `node_add()` result.

```
module_load_include('inc', 'node', 'node.pages');
$content = node_add('osago');
print drupal_render($content);

```

# Answer
> 0 votes
```
<?php
  module_load_include('inc', 'node', 'node.pages');
  print node_add('osago');
?>

```

or

```
<?php
  module_load_include('inc', 'node', 'node.pages');
  $content=node_add('osago');
?>

```

etc etc (you may or may not need the module\_load\_include() depending on how you've set your module up, too)

# Answer
> 0 votes
drupal\_set\_message() or (dsm() if you have devel installed) is your friend...

```
<?php
  $content=node_add('osago');
  drupal_set_message('<pre>' . print_r($content,true) . '</pre>');
?>

```

...and in this case will print out in your theme's message area the structure of a variable, and from that you should be able to see what's going on.

---
Tags: 7, forms
---


# Question
Title: Specify destination folders outside of Drupal root using Drush Make
Is there a way to configure Drush Make so that it would build a structure like:

project\_root

* drupal\_core
* drupal\_contrib

So that next in the build process (that this would form a part of) could symlink the sites/all directory to drupal\_contrib

It would be set up this way as I would prefer the build process to allow an upgrade of Drupal core by simply removing sylinks, upgrading, then re-adding symlinks

I'm aware the build process might as well just loop through some drush dl x statements, or that if Drush Make was used the folders could easily be re-jigged afterwards. Just interested if there is a non-hacky way of doing it first.

Thanks!

# Answer
> 1 votes
I've noticed how I can get part of the way there without moving the downloaded files around

From my main directory I can run

```
drush make --no-core --contrib-destination=modules test.make sites

```

to yield

```
project_name
  - sites
    - modules
    - themes

```

then use a standard

```
drush dl

```

to get core and then use custom scripts to symlink core/sites/all -\> project\_name/sites or something like that.

There doesn't seem to be an option for --no-contrib or anything like that (probably because there isn't much point)

---
Tags: 7, drush
---


# Question
Title: Show the pager on the top and in the bottom of the page (generated by Views)
I created a view and set a pager for it. I is shown in the bottom of the page. Is there any way to show it both in the bottom and in the top of the page?

# Answer
Copy `views-view.tpl.php` template file from `theme` subdirectory of `Views` module to your theme folder, edit it and duplicate fragment of code responsible for printing the pager:

```
  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

```

to where you want it.
> 21 votes

---
Tags: views, paging
---


# Question
Title: How can my module add xml sitemap entries?
I have a module with a page callback handler for the path "products". So if the user navigates to products/apples then the module presents a page about our apples, and if they go to products/oranges then etc. These pages include detail about the various products.

I would like XML Sitemap to be populated from my module. After all, it's my module that knows what products exist, their descriptions etc.

Any hook or anything I can use for that?

# Answer
> 4 votes
The base function you call is `xmlsitemap_link_save()`.

I am unaware of any documentation on how to use this, but nodes get added to the sitemap via `xmlsitemap_node_nodeapi()` which in turn calls `xmlsitemap_node_create_link()`. The code for that should provide some guidance on how to build `$link`.

---
Tags: 7, xml-sitemap
---


title: Views Challenge

text:
# Question
Title: Views Challenge
I have a custom content type called 'Project' that contains a field called 'Category' of type 'List (text)'.

I have created a custom view block that selects all category fields in Projects and used a contextual filter to 'Display a summary', so the block contains an unordered deduped list of the categories.

The block is loaded into a region in a custom template, and output in page.tpl.php using

```
print render($page['other_menu']);

```

Unfortunately, the URLs in the menu appear in this form: href="/projects/Culture-%26-Leisure"

I need them to be all lower case and replace -%26- with an underscore like this: href="/projects/culture\_leisure"

I can make this happen using `preg_replace()`, but suspect it's possible to have the view output the URL in the format I require. I just can't figure how to make the view do this.

# Answer
If I can reverse engineer what you are doing, am I right to assume that you have a project with a title of "Culture & Leisure" that you want linked to /projects/culture\_leisure instead of "/projects/Culture-%26-Leisure" ?

If so, on Drupal 6 at least, this looks like a quick change of pathauto punctuation settings as it's the module that changes spaces and punctuation in titles and such into more presentable urls.

Here it's at 'admin/build/path/pathauto' but I am sure you can find it or its equivalent on your Drupal 7 site pretty simply.

There, just look for what it's doing with the ampersand and tell it to delete it instead of leaving it alone (which ends up in it being encoding as %26), tell it to use a '\_' as the separator instead of a '-' and, last but not least, to also change everything to lowercase.

That should do it :)
> 1 votes

---
Tags: 7, views
---


title: How to load a node on a mini-panel

text:
# Question
Title: How to load a node on a mini-panel
I want to make a mini panel loaded with the fields of the "Node being viewed". But I don't know how to make this happen. Any suggestions?

# Answer
This requires that a node context get passed into the mini panel for it to know what node to pull the data from. Unfortunately there is no way to pass this context using blocks.

You can use page manager to create a node view page which has the correct node context and put the mini panel there.

You can create a view that has a default argument set to get the node id from the URL. Then create a pane display on this view. You can add this view to the mini panel and it will get the node info correctly so you can use blocks.
> 2 votes

# Answer
I do not think so if mini panel is the right choice for this type of requirement. Have a look on this module CCK Blocks.
> 1 votes

---
Tags: panels
---


title: XML node import

text:
# Question
Title: XML node import
I am currently in the process of a proof of concept migrating a existing site into Drupal 7. As of last week I have never seen Drupal, but so far very impressed, however I have one issue.

We have one XML document containing news items that gets updated numerous times per day, I need to create new documents from this. I have seen snippets of php code that load the XML and create nodes, I will need to create our own custom code to do this- however I am not sure exactly where this code would go or how you run it in a Drupal context?

Thanks

# Answer
> 2 votes
Drupal has a Feeds module that may already have some of the functionalities you're looking for. Check it out and it may save you some coding.

If you decide to write your own, then you would have to write your own module. Module development example can be found at http://drupal.org/node/1074360

---
Tags: 7, importing-exporting
---


# Question
Title: Programatically attach a field to a content type
I am in the situation where I need to made some modifications to a content type in my .install file. I know how to create a content type programmatically, just create it via the UI and export, and recreate the form to submit it.

In this case deleting the existing content type and recreating it screws up the existing content type instances, so I need to add an existing field to an existing content type. Is that easy to achieve?

# Answer
Anything in the UI eventually has to call a function, so...

The UI for editing a content type goes to path:

```
admin/content/node-type/NODETYPE

```

This path is "owned" by the cck module. Looking in there, you can dig through the forms and hook\_menu()s etc to see it eventually calls a function:

```
content_field_instance_create($field)

```

which is defined in

```
content.crud.inc

```

inside the cck module's inc directory.
> 1 votes

---
Tags: nodes
---


# Question
Title: Updating duplicate Flags AND one or more Views blocks on a page on Flag click
I have a page where I have several carousel views that can, at times, show the same item/node in each carousel. Such as a most downloaded and a most viewed. I have two different flags (bookmarks and cart) I need to update across the page as well as views blocks that lists out all of the flagged items for each of these.

So as I have been working on just how to do this I have run into some stumbling blocks. First of all I can hook into the flags JS API to initiate this, which is fantastic. I can even identify all of the flags of the type that has been acted upon which apply to the updated flag.

However I have ran into the following problems:

1. When looping through all of the identical items with say the bookmarks flag I don't seem to have a way to differentiate it from the other flags on the page that need to be updated. My concern is that by looping through all of them I will inevitably leave the flag I clicked on in the same state and all of the other duplicate flags on the page in the new state.

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) { //Your code here });
2. I want to prevent the flags JS from showing the popup messages on each click such as "item added to bookmarks" and instead pass that to jGrowl. I know how to generate it in jGrowl, I just need to figure out how to capture that message and show it my way.
3. Finally I need to update the related views block on the page when this is done. Say the bookmarks list block.

So what I would like to know is first, how do I deal with updating the same item's flag on multiple places on the page when it has duplicates? Secondly I want to know how to capture that message and redirect it to my tool (jGrowl). Lastly is how do I update a view block on a page with AJAX?

I want to do all of the updates without reloading the entire page.

Currently I am running this on Drupal 7 with Views 3 and using Nice Messages to generate system messages in a Growl-like format.

Thanks, Patrick

# Answer
I just ran into the same problem. This is how I handled updating duplicate flags on a page:

```
    $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {

        if(data.flagStatus == "unflagged"){
            $('.flag-favourite-' + data.contentId + ' a').each(function(){
                if(!$(this).find('a').hasClass('unflagged')){
                        ($(this).html(data.link.innerHTML));
               }
            });
        }
        else{

            $('.flag-favourite-' + data.contentId).each(function(){
                if(!$(this).find('a').hasClass('flagged')){
                        ($(this).html(data.link.innerHTML));
               }
            });

        }
    });

```

change out the term favourite with the machine name of you flag and it should work...
> 1 votes

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


title: Services 3 and node locations

text:
# Question
Title: Services 3 and node locations
I'm trying to create a node via services 3 in Drupal 7. The node os created, but when I try to pass the location parameters in, it does not work. If I pass an lid that already exists, it seems to reference that location; if I try to pass a new lid, the information is not registered.

Is there such thing as a location resource for the services module? THis is the JSON string I am using.

```
{
"title":"test",
"type":"test_type",
"locations":[
      {
         "lid":"4",
         "name":"",
         "street":"",
         "additional":"",
         "city":"",
         "province":"",
         "postal_code":"",
         "country":"us",
         "latitude":"40.663062",
         "longitude":"-73.969760",
         "source":"1",
         "is_primary":"0",
          "locpick":{
            "user_latitude":"40.663061",
            "user_longitude":"-73.969760"
         },
         "province_name":"",
         "country_name":"United States"
      }
   ],
}

```

# Answer
> 1 votes
```
var node = {
                title: "Sample Location",
                body: {
                    und: [{
                          value: 'Sample Body'
                          }]
                },
                field_location_type: {
                    und: [{
                          latitude : '37.4861987023',
                          longitude : '-122.2312',
                          country_name : 'United States',
                          province : 'CA',
                          city: 'My City',
                          postal_code : '12345',
                          name : 'Place Name',
                          }]
                },
                type: 'location',
                language: 'und',
            };

```

This sets a variable 'node' for Javascript. CCK field is "location\_type". All the other parameters are being inserted into the node (city, postal\_code,...) , but the Lat/Lon is still not being posted. I suspect that it may be because a node can have many 'locations'. Any help here would be great.

Take a look at the debug log: admin/reports/dblog for the json interaction. You need to turn on Services Debug "Debug mode enabled" located at admin/structure/services/list/api where 'api' is the endpoint.

---
Tags: nodes, services
---


# Question
Title: How to display the related node content in a block?
How can I display the related content for a specific node (type product) in a block? I would like to display the image, title and a trimmed body of the related content (from the same company) at the end of the node.

# Answer
You can use the Featured Content module for that.

Alternatively, you can also use the Views module by filtering your content using the node of the current page as an argument and using taxonomy or node reference to relate the content.
> 1 votes

---
Tags: views
---


title: Print created menu directly in a page

text:
# Question
Title: Print created menu directly in a page
I have created a menu like france menu. I just want to print it using print\_r statement. Is it possible? I know menu block is there. But i don't wanna use it.

# Answer
> 5 votes
Try this:

```
$menu = menu_navigation_links('menu-your-custom-menu-name');
print_r (theme('links__menu_your_custom_menu_name', array('links' => $menu)));

```

Source: How to print a menu in Drupal 7 ? and the next comment is also useful: printing custom secondary menu when the user is logged out.

Changelog for Drupal 7: Use #theme='links\_*MODULE' or #theme='links*\_MODULE\_EXTRA\_CONTEXT' when adding links to a render array.

**Edit:** new version using `menu_tree()`

```
$menu = menu_tree('main-menu');
$menuhtml = drupal_render($menu);
print_r($menuhtml);

```

---
Tags: 7
---


# Question
Title: Views PHP Filter - Filter Results by Role
I looked a lot of places and couldn't find a way to filter the results of a view based on the nodes a user could actually edit. So I used Views PHP Filter and some custom code to make it happen.

Comments and improvements welcome.

```
global $user;
$type = array();
$nid_list = array();
$perms = array();
foreach($user->roles as $role) {
  $role_perms = db_fetch_array(db_query("SELECT `role`.`name`, `permission`.`perm` FROM {role} INNER JOIN {permission} ON `role`.`rid` = `permission`.`rid` WHERE `role`.`name` = '%s'", $role));
  $perm_temp = explode(", ", $role_perms['perm']);
  $perms = array_merge($perms, $perm_temp);
}
foreach($perms as $perm) {
  $pos_edit = strpos($perm, "edit");
  $pos_content = strpos($perm, "content");
  $pos_products = strpos($perm, "products");
  if (($pos_edit !== false) && ($pos_content !== false)) {
    $perm = substr($perm,9,strlen($perm)-16);
    if (!in_array($perm, $type)) {
      $type[] = $perm;
    }
  } else if (($pos_edit !== false) && ($pos_products !== false)) {
     $perm = substr($perm,9,strlen($perm)-18);
     if (!in_array($perm, $type)) {
       $type[] = $perm;
     }
  }
}
foreach($type as $ctype) {
  $nids = db_query("SELECT `node`.`nid` FROM `node` WHERE `node`.`type` = '%s'", $ctype);
  while($row = db_fetch_array($nids)) {
    $nid_list[] = $row['nid'];
  }
}
asort($nid_list);
return $nid_list;

```

# Answer
> 1 votes
I would take the ORDER BY out of your last query and let views sort things itself. After all, you may want to sort the nids by date or something later on, so why do things twice?

And also change your query style to use the drupal syntax, like:

```
SELECT nid FROM {node}...

```

# Answer
> 1 votes
Be careful using php code in this way. This option in views is intended for examination during development and not for an active site. For this code located in the database to work you have to turn on php interpretation and this could let a user with an understanding of php code get access to unauthorized materials on the site. I recommend that you create a custom module and and a hook to views. I'm not certain which one, but the available hooks are discussed in the advanced help section for views.

---
Tags: views, users, input-formats
---


# Question
Title: Delete a feature but keep the content created by it
Is it possible to keep the data created by a feature after deleting feature itself?
I created a migration feature that is really just a one off; I would want to delete it without losing the nodes created from it.

# Answer
Features module is a way to export most of the settings normally stored in the database into code. If you delete the feature, you delete the code which deletes everything.

The cool thing about features is you can change the settings for things (views, panels, etc) at any time and those changes get stored in the database. Once they're stored in the database it should be OK to delete the feature (though I haven't tried this myself).

The easiest way to do this would be to go into each item that your feature has and re-save it. For example, if your feature had a view called "News" you can go to Structure \> Views \> News \> Edit. Then click save on that view. If you look at your feature, it should now say "Overridden."

Once everything is overridden, it should be OK to delete the feature. Make sure you do a backup of everything and try disabling the feature first to make sure everything you need doesn't disappear.
> 6 votes

---
Tags: 7, features
---


title: Aliases for user profile URLs

text:
# Question
Title: Aliases for user profile URLs
For example, the URL http://example.com/user/20/edit/cocktail?destination=user%2F20 leads to a page with the form to add content.

I want to create an alias like bartender/add/cocktail, or (if possible) bartender/profile/\[current-loggedin-bartender-name\], \[current-loggedin-bartender-surname\]/add/cocktail.

Is this possible? How can I do it?

# Answer
> 1 votes
Those kinds of aliases cannot be implemented by the Pathauto module because it is difficult to add tokens into the menu settings. To help with this in the past, I used the me aliases module.

> Provides shortcut paths to current user's pages, eg user/me, blog/me, user/me/edit, tracker/me etc.

It has a Drupal 7 release which has been released on June 8, 2019. There is an issue open to port the module to Drupal 8/9: Port Me module to Drupal 8 / 9.

# Answer
> 0 votes
Menu tokens is another option that looks a bit more robust than me aliases but they both now have token replacements and it is still in alpha3 as of now.

Menu Token module

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


title: ubercart checkout causes node to update

text:
# Question
Title: ubercart checkout causes node to update
On a site I manage we have a view of recently updated products. The problem is that once a user purchases a product, that product is updated, which shoots it to the top of the list.

As far as I can tell there's no reason for a node update to be triggered simply because the product was purchased.

My first thought was the stock. However, uc\_stock is directly calling db\_query on uc\_product\_stock table and not touching node, or is it doing a node\_load/node\_save.

The closest I've found is that the update is triggering the nodeapi hook with the 'update' op. nodewords is picking it up as an update operation and I can see it in the dblog.

Any ideas?

# Answer
Perhaps install and enable devel, and then look at the SQL queries to get the offending query which might give you clue about some other module that's doing an update.
> 0 votes

---
Tags: 6, nodes, ubercart
---


# Question
Title: Node template only on specific page (Drupal 7)
I've been reading through a ton of Drupal 7 theming docs but can't seem to find my answer.

Here's what I'm trying to do. I have two content types `article` and `feature`.

Nodes of *both* content types are displayed on my /blog page via the Views module. All working great so far.

When the node of type `article` is listed, it uses the node--article.tpl.php template, and when a node of type `feature` is listed on the blog listing page, is uses node--feature.tpl.php.

This is all as expected, *BUT* for `feature` types, I want to display the node--article.tpl.php template *only* on the /blog page, and use node--feature.tpl.php (the default) for that type otherwise.

In other words, I'd like to keep the templates separate, but use the same template for both `article` and `feature` types on the blog listing page (node--article.tpl.php).

Is there way to create a node-page-specific template file (use this template for this node ONLY if on this page)?

# Answer
add template.php:

```
function THEMENAME_preprocess_node(&$vars) {
  if (request_path() == 'specific/page') {
    $vars['theme_hook_suggestions'][] = 'node__specific';
  }
}

```

and create file node--specific.tpl.php in theme dir
> 8 votes

# Answer
If you're using views why not just switch to field display rather than node display? You could probably then just copy your node--article.tpl.php to the right views tpl and it would just pick it up.
> 0 votes

# Answer
While considered evil in certain circles, you could certainly put something like:

```
<?php

$foo=explode('/',$_GET['q']);

if ($foo[0]=='blog') {

    ALL YOUR BLOG SPECIFIC TEMPLATE PHP GOES HERE

} else {

    TEMPLATE PHP FOR EVERYWHERE ELSE GOES HERE

}

```

in your node template file.
> 0 votes

---
Tags: theming
---


# Question
Title: cache_token table doesn't exist after Drupal 6 to Drupal 7 upgrade
I recently created a D6 site to import some content using the D6-only import\_html module, then upgraded it to D7 (in a slightly roundabout way I can describe, but shouldn't be relevant to the question). Since doing so, whenever I enable new modules and am sent to /admin/modules/list/confirm I see Drupal error messages like the following:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'drupal7\_gimported.cache\_token' doesn't exist: TRUNCATE {cache\_token} ; Array ( ) in cache\_clear\_all() (line 169 of /Users/tomash/Sites/drupal7/includes/cache.inc).

The modules do seem to install correctly, but the error is annoying and alarming. I would just copy a cache\_imported table from a clean Drupal 7 install, but I wanted to check whether this is the right approach in general, and whether the error points to deeper problems.

### Relevant information, which I can add to

* I had the Token module installed in the Drupal 6 installation
* I've enabled the Drupal 7 version in the upgraded Drupal 7 installation
* I'm running this all on my localhost, which has rarely yielded errors before

# Answer
After enabling back your module have you run `update.php` to ensure all needed queries are executed ?
It seems its the first update the token module runs.

```
/**
 * Add the cache_token table.
 */
function token_update_7000() {
  $schema['cache_token'] = drupal_get_schema_unprocessed('system', 'cache');
  $schema['cache_token']['description'] = 'Cache table for token information.';
  db_create_table('cache_token', $schema['cache_token']);
}

```
> 2 votes

# Answer
Just run http://example.com/update.php and you are done. Nothing is needed. But, keep in mind that you need to run after the modules are enabled even though it throws any error. If still it doesn't fix it go for a dev version of the module. Sometimes it helps me. :)
> 0 votes

---
Tags: 7, caching, upgrading
---


# Question
Title: Show jCarousel if number of items are more than 3
I am using the jCarousel Views module; I want to hide the view when the number of items are not greater than 3. How do I do it?

# Answer
You can use JCarousel views as block display and then set a visibility condition by executing custom php condition test code (This will require to enable PHP Filter module)

```
$result = views_get_view_result('view-name', 'display_id');

```

Then you can analyze the `$result` and count the number of results. Most probably you need to do ....

```
if(count($result)<3)
    return FALSE; //Would not let to show that block
else
    return TRUE; // Would let to show

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Change where the theme gets its files from
I'm a beginning developer and I am working in this one **Drupal 6** website that has multiple websites in the root. To add to the complexity, I am working with the module Mobile\_tools to direct users to a mobile theme.

My issue lies with the sharing of images. When users are directed to the mobile theme, I want to find a way to specify where the website grabs it's images from. It seems that by default, it grabs them from the /sites/all/files rather than the /sites/all/themes/theme/files location.

What would be the best way to go about changing this location? I was thinking of implementing a hook override, but have no idea where to or how to begin.

# Answer
drupal\_get\_path and path\_to\_theme are the two functions that will be usefull for u.
> 0 votes

---
Tags: 6, hooks
---


# Question
Title: How can I include radiobuttons to a view's results?
I want to include two radio buttons to EVERY view's results, so a user can select one of them. This is actually a view with users results. Next to each result the following radio buttons will appear: "Active", "Suspend this member" and "Delete this member". How can I make these radio buttons appear on each view result? Thanks

# Answer
> 2 votes
Is it very important to you to have radio buttons exactly like you describe? If not, I can recommend the Views Bulk Operations (VBO) module. VBO is a popular module which allows you to select views rows and perform a certain action on those rows. Each row gets a checkbox and you select the action to be performed with those rows using a select box. Here is a screenshot to illustrate that:

I think VBO is by far the most mature option available to solve your problem. If you insist on having the radio buttons in your view and you don't mind writing code yourself, have a look at Views Form Field (interesting, but no releases yet), or Create the "View as form" style (work-in-progress in the Views issue queue).

---
Tags: views
---


# Question
Title: How to keep in sync git repository and related htdocs directory?
I use the following set up for my `@dev` site:

**(a) ../git/repository/dev**

where I keep version control using git,

and a separate

**(b) ../htdocs/dev**

that I have an *almost* exact copy of *git repositor* (a) used by the http server

How to make sure *git repository* (a) is always in sync with *http* (b) ?

I don't want to version control (b) directly from various reasons.

# Answer
use the "post-update" hook in the /hooks directory provided in your .git directory to push a copy (sans -gitignore- the files not needed) each time you make git commits to your dev files
> 1 votes

---
Tags: version-control
---


# Question
Title: Best practice for using location names as part of taxonomy?
I'm setting up my taxonomy vocabularies for describing my node content. Most of it's fairly straight-forward, but I'm stuck on how to describe the location data for my nodes.

I have a small hierarchy of place names for a limited geographic region that my site covers. Should I continue to use taxonomy to create a vocabulary, or should I be using the location module? I will be having location-specific content in the node, such as a Google Map to show the location of venues etc. Can location module content be tied up to a taxonomy vocabulary?

# Answer
It depends of your goal:

* If you want to cover large areas like cities, it's better to use Taxonomy as it will be easier to build (for example) a view (or map) of all node from this city.
* If you want very precise geolocation (like the position of a store in a map), then go for location. Regarding Location module, it may be overkill for simple Lat./Long. positioning and a simple CCK field for each should be enough.
* You can of course have both Taxonomy and Lat./Long. for your nodes and use the one appropriates regarding your context.

If you have time, I'll recommend the listening of Acquia Podcast 22: DevSeed On Mapping in Drupal.

> Being able to display maps in Drupal is a powerful feature, and can also be confusing to implement. Join us as we talk with Ian Cairns, Tom MacWright, and Robert Soden from Development Seed about how it is done and the different options available for displaying great maps.
> 4 votes

# Answer
I think the right way'd be to create location terms and while saving the node, the location address fields should copy from the taxonomy term. Using taxonomy terms help your site keep organized.

For example create term name for Delhi as Delh i but have "City Name" from Location input copy it from the taxonomy current taxonomy term Delhi.

How to handle it technically is what I've asked here: Autopopulate "Postal Code" from taxonomy in Location module
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I mirror a database from remote Linux into Windows localhost?
I would like to mirror Linux *dev.example.com* into Windows *dev.example.com.local* properly to be able to do development locally.

1. I have already set up *xampp* and *hosts* (dev.example.com.local)
2. I have created localhost mysql database instance (dev).
3. I have set up Drupal 7 settings.php on local.
4. I can export remote db into sql.zip file and I can import it into local db

The key question I have now is **how to properly handle mysql export and import to make sure both local and remote mysql instances are in sync?**

I bet Step 4 is not enough here.

# Answer
> 2 votes
Step 4 is enough, they both will be in sync until you change data on one or the other instance.

As a bonus tip, you can ease this procedure by using `drush` to sync your environnements, via the use of drush aliases.

More details on this here.

Good-luck friend, happy coding.

# Answer
> 1 votes
You need only add an important step 5 to the above list:

1. drush clear-cache all

Unfortunately, drush sql-sync is not currently supported on Windows. Patches welcome!

# Answer
> 1 votes
A very hand module for this is backup and migrate. It creates or intalls a complete backup of your db with one mouse click.

---
Tags: 7, database, migrations
---


# Question
Title: Variable created in hook_preprocess_node is not available to template
I have this preprocess function in my theme:

```
function hotness_preprocess_node(&$vars) {
  $node = empty($vars['node']) ? FALSE : $vars['node'];
  $vars['hotness_is_article_page'] = ($node && node_is_page($node) && $node->type == 'spot') ? TRUE : FALSE;
}

```

The other stuff I do here (not shown) works fine. However, I get an undefined error when I try to use $hotness\_is\_article\_page in my theme tpl files (specifically region--branding.tpl.php). I am using Omega, if that matters.

For some reason I only seem to be able to create variables accessible in tpl files in my hotness\_preprocess() function, but not page or node hooks. This is not ideal, as hotness\_preprocess() runs several times per page load.

What am I doing wrong?

# Answer
> 6 votes
The variables added from `hook_preprocess_node()` are only available in node.tpl.php, or any other node template that Drupal will pick up because any suggestion contained in `$variables['theme_hook_suggestions']` (Drupal 7), or `$variables['template_files']` (Drupal 6).

To add a variable used by a region template file, you need to use a different preprocess function: `hook_preprocess_region()`, or `hook_preprocess()`. The latter is a generic preprocess function; the second parameter passed to that preprocess function tells it which theme hook is going to be preprocessed.

This means that, by default, the region preprocess function doesn't have access to `$variables['node']`; if you want to access the node object associated with the page being viewed, if there is one, you need to use similar code used in template\_preprocess\_page() and add the following line to your preprocess function:

```
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

```

The function returns `FALSE` if the page is not associated with a node; this could happen, for example, if the user is visiting example.com/user/1.

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


# Question
Title: How can I trace module dependencies in Features?
I have a site with several module created with the Features module. I've just noticed that one of the modules created with Features (we'll call it module B), has a dependency on another module created with Features (module A). As far as I know, there should be no connection or dependency between the two modules at all.

Is there a way to track down which aspect of feature B is creating the dependency on feature A since I'm almost positive it is doing so in error?

# Answer
Look through the info file of Feature B and look for anything known to be added or modified with Feature A.

My guess (with little information) would be that Feature A defines a field/cck field and Feature B either uses that in a content type or view.
> 1 votes

---
Tags: features
---


# Question
Title: How can I link an image of a jCarousel to a certain link?
I would like to link the different images of my jCarousel to different specific links depending on the actual image.

# Answer
> 5 votes
I assume you're using views and jCarousel and Drupal 7.

On same content type that you have your image fields, add a new link field. Add this link field to your view but check the `Exclude from display` checkbox, set the Formatter to `URL, as plain text` and make sure the link field is before of your image field in order.

Edit your image field settings in the view and, under `Rewrite Results`, check `Output this field as link`. Scroll down to the replacement patterns and copy the pattern that references your link field. Put this pattern in the `Link Path` text box.

---
Tags: javascript
---


# Question
Title: saving JS settings in theme_settings.php file
i am working on a responsive D7 theme and need some JS settings to be saved via theme settings form not a custom module. i did following codes to give what i want but it seems that Using drupal\_add\_js() function to add JS settings in theme\_settings.php file doesn't work. could you please point out what is the problem and is there any alternative solution? some of my codes in theme\_settings.php file is as followings:

```
/**
* Implements hook_form_system_theme_settings_alter()
*/
function glossy_form_system_theme_settings_alter(&$form, &$form_state) {
    $theme = alpha_get_theme();

    $lib_options = false;

    /** add mobileMenu options to theme settings */
    if (isset($theme->settings['libraries']['glossy_mobileMenu'])) {
        $lib_options = true;
        $form['alpha_settings']['glossy_lib_options']['mobileMenu'] = array(
            '#type' => 'fieldset',
            '#weight' => -10,
            '#title' => t('mobileMenu options'),
        );

        $form['alpha_settings']['glossy_lib_options']['mobileMenu']['mobileMenu_selector'] = array(
            '#type' => 'textfield',
            '#description' => t('Select the CSS selector of the container that all inner menus will be responsive. e.g. %example', array('%example' => '.navigation')),
            '#title' => t('responsive menu container selector'),
            '#default_value' => theme_get_setting('mobileMenu_selector'),
        );

        $form['alpha_settings']['glossy_lib_options']['mobileMenu']['mobileMenu_title'] = array(
            '#type' => 'textfield',
            '#description' => t('e.g. Select a page'),
            '#title' => t('First option text'),
            '#default_value' => theme_get_setting('mobileMenu_title'),
        );

        $form['alpha_settings']['glossy_lib_options']['mobileMenu']['mobileMenu_indent'] = array(
            '#type' => 'textfield',
            '#description' => t('e.g. !string', array('!string' => '   ')),
            '#title' => t('string for indenting nested items'),
            '#default_value' => theme_get_setting('mobileMenu_indent'),
        );

        // add submit handler
        $form['#submit'][] = 'glossy_mobileMenu_submit';
    }

    if ($lib_options) {
        $form['alpha_settings']['glossy_lib_options']['#type'] = 'fieldset';
        $form['alpha_settings']['glossy_lib_options']['#weight'] = -10;
        $form['alpha_settings']['glossy_lib_options']['#title'] = t('Libraries options');
    }
}

function glossy_mobileMenu_submit($form, &$form_state){
    // Add the mobileMenu options variables.
    drupal_add_js(array(
        'responsive_menu_options' => array(
            'selector' => $form_state['values']['mobileMenu_selector'],
            'title' => $form_state['values']['mobileMenu_title'],
            'indent' => $form_state['values']['mobileMenu_indent'],
        ),
    ), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

```

thanks in advance.

# Answer
> 3 votes
I think you problem is this: drupal\_add\_js needs to be called at runtime. It's not some kind of registry function that adds your js file for every future page request. In other words, your code only adds the js when the form is being submitted.

Instead of calling drupal\_add\_js in your submit handler, store a variable using variable\_set() to indicate that the js must be added. In your template.php file you can use the \_preprocess\_page function to retrieve the setting using variable\_get() and call drupal\_add\_js if needed.

---
Tags: theming, javascript
---


# Question
Title: How to redirect exposed view filter form submission?
I have a view which is displayed from a theme method using views\_get\_view() and view::preview (see below). This view has an exposed filter. Unfortunately the exposed filter form does not work. When I submit the form it calls the wrong URL.

The wrong URL looks like this

```
http://domain?date_start=12

```

For comparison, the link of the sortable columns (which work as expected) does look like this:

```
http://domain/myselfcare/communications?order=destination&sort=asc&date_start=12

```

How can I fix this?

```
function theme_win_care_communications_page( $customer, $form, $form_state) {
  global $user;
  $output = '';
  watchdog('win_care', 'communications_page user=' . $user->uid . ', cust=' . $customer->id);
  $communications_view = views_get_view('drp_communications');
  $output .= $communications_view->preview('default', array($user->uid));

  // add an explanatory text
  if ($customer->reseller_id==33) { // mbudget only
    $output .= t('Note M-Budget: tariff is a function of the call time (in lots of 10 cents).');
  }
  else {
    $output .= t('Note: setup fee of 0.50 per call, minute rate according to current tariffs');
  }

  return $output;
}

```

# Answer
> 1 votes
Thanks for the additional info, it adds a lot of light to the issue. I am not exactly sure what is going on but maybe an explanation of what drupal does might give you an "A-ha! That's where I entered some info wrong" moment:

In the code, drupal/views/etc uses form redirects:

```
$form_state['redirect']= VARIABLE OR CODE TO SET IT TO A PATH

```

that is obviously mangling the redirect into:

```
http://domain/?date_start=12

```

What is interesting here is it is setting that url to the date\_start value instead of adding that to the url:

```
http://domain/myselfcare/communications?order=destination&sort=asc&date_start=12

```

So here, instead of adding ?date\_start=12 to the end of

```
http://domain/myselfcare/communications?order=destination&sort=asc

```

it's replacing it all (additional vars get the ?= changed to an &=)

So, I'd look at how you are defining date\_start in your view forms and see if anything odd pops up there. That or in your theme code setting the redirect to that directly.

---
Tags: 6, views
---