# Question
Title: What is the purpose of the "Views: views_view" component?
Using the Features module, I notice there is a "Views: views\_view" component, when creating a feature, but I don't see any setting for that component.

I thought it would be list the views enabled in the site, but that doesn't happen, even if I have two views enabled.

What is the purpose of that component? Why isn't showing any settings?

I have tried with both the latest release candidate, and the lastest development snapshot, but the result doesn't change.

# Answer
> What is the purpose of \[the "Views: views\_view"\] component?

As you suspected, to allow views to be exported into a features module.

> Why isn't showing any settings?

I do not know. One possible explanation is, that all the enabled views are provided by other modules via an implementation of hook\_views\_default\_views(). The Features module itself exports views by writing an implementation of hook\_views\_default\_views(), so the Views module cannot distinguish between the two versions of the view. That's why the Features module does not allow views to be exported, that are provided by other modules.
> 3 votes

---
Tags: 7, features
---


title: Help learning OpenLayers for D7

text:
# Question
Title: Help learning OpenLayers for D7
I need to learn more about OpenLayers for Drupal 7. There is a ton of documentation for D6, some of which is helpful and some which isn't.

I'd like advice or suggestions for tutorials for a few different pieces..

When creating content, I want users to add a point or an area using a map. I know this is GeoField with the OpenLayers Map widget (so they don't type anything, but select visually), but I'm not sure how to then use this data in views.

In views, I need to create a map that displays the content. I want to set the default area based on the users' location.

Thanks.

# Answer
> 2 votes
This is the best tutorial I'm aware of: http://www.istos.it/blog/mapping/openlayers-and-addressfieldis

# Answer
> 2 votes
The Drupal 7 Getting Started Guide has been started, but still needs some love. A good place to begin (and add to the wiki as you go along).

# Answer
> -1 votes
this is very good: http://www.syntux.nl/blog/basic-setup-drupal-7-openlayers-geofield-views-3.html

---
Tags: 7, location, javascript
---


# Question
Title: Is there a way to intercept a list of NID's created by a view and use them as a filter for another view?
I am at the point in Drupal experience where I am attempting to solve site design challenges at the custom code level using Drupal and Views APIs. As usual, my apparently simple attempt to solve a problem has demonstrated to me how much I don't know yet!

I have a node-reference field that points to a 'related facts' content used by many different content types and subcategories for each of these types. While I can create a relationship and display the 'related facts' for a view, there are problems. For one, I want the related facts put in a separate block and to display a single list of related facts for the entire list of articles provided by the view. Views does not handle any duplicates for multiple nids with the same 'related facts' reference well. In addition, I would have to generate separate 'related facts' views for each content type and subcategory which will be quite a large number.

If I could create a separate related facts view that can accept a list of nids as an argument, the related facts view could be simplified. So my question is how to go about this. While it may be possible from within views, I am seeking a **custom module php solution**, so I need to achieve the following:

1. Extract the results of any of the 'content type' views as a list of arguments. In addition to displaying the view results, I need to load the list of NIDs that are being displayed.
2. Call the related facts view and pass the list of nids to it to use as a filter or contextual filter in the 'related facts' view.

**Additional Information:**

Using this strategy I began by defining a view and attempting to extract the results from it. This attempt led to a problem finding the results in the view object (see this question). Once I get the results I will need to generate another view that has those results as filters. I have seen views implemented from code as include files where all the parameters are coded, but have not found examples that define and generate a view and manipulate the results using a php function. Any examples or links would be appreciated.

**Thus Far:**

Two answers have addressed the process for applying the results of a view and placing it in another view as a contextual filter. But I still face the problem of having dozens of content types with at least a dozen view content pane variations in each. Instead of directly linking each view to the related facts, I will need to have the any of my view1 content views pass its results to a single, separate 'related fact' view.

```
CONTENT TYPE    SUB-CATEGORY       RELATED FACT (nid)
    Type 1 --------- General Info       101, 105
                     Specifications     103, 105
                     Inspections        102
                     Quality
                     etc...
   Type 2 ----------General Info       101, 106
                    Specifications     102, 103
                    Cost factors       107
                    etc...

```

View1 finds a specific content type and contains various sub-category articles sorted by the value in a subcategory field. In addition it contains a node reference field for related facts. View one filters for a content type and a subcategory and has exposed fields for display and a hidded field with thte related fact reference nodes.

View2 filters for 'related fact' articles and contains a contextual filter set for nid (although the setting applies to the URL)

Using the code in Letharion's answer, the foreach loop in line 6 is compiling a list of the article ID's, not the related fact id's (the articles hold a reference to related facts, but the related facts do not have a node reference to articles). I need to extract the related fact id's from the facts field in each node. I have included the facts field in the View1 definition, but cannot find the result since the command dpm($node); has been crashing and I don't know where the values are stored in the array.

Since there will be more than one View1 cloned for different content types I thought it may make sense to use hook\_views\_post\_execute and have coded it as follows:

```
function mymodule_views_post_execute (&$sourceview) {

  $nids = '';
  foreach($sourceview->result as $node) {
    $nids += $node->nid . ',';  //I need field name for $node->facts

  }

  $nids = rtrim($nids, ',');
  $view = views_get_view('get_related');

  //dpm($nids);  // Fatal error: Cannot unset string offsets...

  $view->execute_display('panel_pane_1', array($nids));
  }

```

Finally, I am not sure if I have to direct the display of the view to the proper location or is this done simply by placing the related facts content pane in the panel location through the Panels UI and let panels theming handle the rest.

# Answer
> 3 votes
Just off the top of my head

With views 'get\_nids', and 'get\_related', get\_related taking a `nid` argument, that is set to accept multiple values. This option is hidden under "more", at the bottom of the configuration window.

**Option 1:**

```
$view = views_get_view('get_nids');
// Repeating query, ensure the View is set to cache the results.
$view->preview('display_machine_name', array($arg1, $arg2));

$nids = '';
foreach($view->result as $node) {
  $nids += $node->nid . ',';
}
$nids = rtrim($nids, ',');
$view = views_get_view('get_related');
$view->execute_display('display_machine_name', array($nids));
print $view->render();

```

**Option 2:**

Add a "context" display type to get\_nids, and pass that context on as the argument to a content pane display of get\_related. Unfortunately, I would have to guess that Views contexts lacks support for compressing multiple results into a single context, so that may require a feature request in Ctools.

**Option 3:**

Beth has an excellent suggestion in a comment, which is using EntityFieldQuery, for when you want a pure code solution, that would also work with MongoDB. Views though has the advantage that most of the work can be done in a UI, which is often convenient.

# Answer
> 2 votes
Seeking out fields within a node and returning a list of NIDs is the exact thing that EntityFieldQueries was born to do. (See also: my own question on the topic).

An example from my code, which runs upon webform submission, and in which I seek out nodes of type "Quiz Anzwer Key" to find the one(s) with field "Quiz Reference" filled in with the NID of the currently-validating webform:

```
    $arg = arg();
    $nid = $arg[1]; //this finds us the NID of the current page
    $query = new EntityFieldQuery;  // this EntityFieldQuery searches through Entities for Nodes that point to the current Webform.
    $result = $query
        ->entityCondition('entity_type', 'node') // find nodes
        ->propertyCondition('status', 1) // that are published
        ->propertyCondition('type', 'quiz_answer_key')  // of type Quiz Answer Key
        ->fieldCondition('field_answer_quiz', 'nid', $nid, '=') // that point to the current node in their Quiz reference field
        ->execute(); // do the query
    $results        = $query->ordered_results; //grab the results

```

Then, if you want to actually load values from fields in the nodes, you'd use `node_load` to grab more info out of the nodes you want, like so:

```
    $ans_key_id     = $results[0]->entity_id;
    $ans_node       = node_load($ans_key_id);       //once the correct node has been identified, load the contents of that node and suss out the answers

```

Now `$ans_node` is an array (or object, I forget) that contains all the info in all the fields in the node. Voilá!

# Answer
> 0 votes
Ok a coded solution (there area few) but here is one:

1. **Create a view** that gets all the nid's output these nid's as a comma de-liminated list, you can do this by using fields as your output and setting your style settings to Style Unfomatted, row style fields -\> make the nid field inline and use a comma as a separator.
2. In your module **create a function** that calls this view and gets the output
3. **Create your second view** (or display) use this function as an argument in your second view that actually does the display output, so under arguments the argument should be node:nid, the *Action to take* should be set to "provide default" and you then use the PHP code setting to call your function: return mymodule\_get\_nids(); ensure he checkbox "allow multiple terms per argument" is ticked

**Step 2 code**

```
function mymodule_get_nids() {
    $view = views_get_view('getmynids')) // View name
        $view->set_display('mynids'); // Display name
        $view->execute();
        if ($view->result) {
         return $view->preview(); // Can't remember if this needs to be echo or return try both.
        }
    }
}

```

Should this be a separate answer?? or an edit??

---
Tags: views
---


title: Managing modules - site overriding

text:
# Question
Title: Managing modules - site overriding
I have drupal site, where modules are centrally managed. In case I want to have different version of module I put it to sites/my-site-name/modules/moduleX.. but now I want to go back to the centrally managed version..

I cannot turn it off as it's in dependency with field and some other modules. If I just delete it, site runs with error which prevents me from clearing cache (which would start using the central version of module again). I could change it via myPhpAdmin by chaning records in table 'system', but after changing them to old path (/sites/all/modules/moduleX) it doesn't look for the new file - I guess there's a need for cache clear..

seems stupid and easy but cannot figure it out. any ideas?

---

edit: maybe just deleting everything from "cache\_bootstrap" table will do?

# Answer
> 1 votes
Clearing caches should definitely do the trick. You can manually truncate each of the tables whose name begins with `cache_`, or (far preferably) you can install Drush.

The Drush command to clear caches is simply:

```
drush cc all

```

---
Tags: 7
---


title: Set up *only* module configuration page

text:
# Question
Title: Set up *only* module configuration page
I have a custom module that has a settings page. Problem is, something about my hook\_menu settings is also putting a link to this page in the main admin menu (along with Dashboard, Content, etc).

How do I keep my settings page without seeing the main menu item?

```
  // admin config option
  $items['admin/configuration/content/brd_contact'] = array (
     'title' => t('BRD Contact Form'),
     'description' => t('Configuration options for the BRD Contact Form module.'),
     'page callback' => 'drupal_get_form',
     'page arguments' => array ('brd_contact_admin'),
     'access arguments' => array('administer brd_contact'),
     'type' => MENU_NORMAL_ITEM
  );

```

# Answer
If you want to remove the link from the admin menu altogether, you just need to change the `type` to something other than `MENU_NORMAL_ITEM`. `MENU_CALLBACK` is the standard for this type of thing:

```
$items['admin/configuration/content/brd_contact'] = array (
  'title' => t('BRD Contact Form'),
  'description' => t('Configuration options for the BRD Contact Form module.'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array ('brd_contact_admin'),
  'access arguments' => array('administer brd_contact'),
  'type' => MENU_CALLBACK
);

```

After you clear Drupal's caches the link should be gone from the admin menu.

If instead you want to move the link from the top level of the menu into the sub-menu under 'Configuration', then you just need to change the string 'configuration' to 'config' in your path, to match the other system menu paths:

```
$items['admin/config/content/brd_contact'] = array (...

```

You'll need to clear the caches before that'll take effect too.
> 4 votes

---
Tags: hooks, routes
---


# Question
Title: Are there any tutorials available for node reference url
Does anyone have a tutorial link to show me how to use node references with custom content types, ie. QUESTIONS and ANSWERS, in D7?

# Answer
Google will find you masses of tutorials.

e.g. http://www.youtube.com/watch?v=0CHC8I9xZIg

Above is the first hit in the video search. But there is much more.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Set node action for specific content type
I want to set a trigger to redirect when a node (or comment) on a certain content-type is created.

I have 2 hurdles here:

1. The Trigger module doesn't seem to offer any distinction between content types. Will I have to write some sort of hook?
2. I can create an action to redirect to the specific URL, but it always shows up under the 'system' category and is then not in the dropdown list when I go to set it for creation of every content type.

# Answer
The Rules module will be able to handle this, it's a next-generation version of the actions/triggers that are included with core:

> The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

You can use the "After saving a new comment" event for the comments part, and the "After saving new content" event for the content part.

In both cases you'll be able to use conditions on your rules to make sure the actions are only fired for your required content types.
> 1 votes

---
Tags: 7, nodes, rules
---


# Question
Title: Help with view styling - template/css/whatever
Our client saw the schedule view of DrupalCon Denver's site and wants one of their conference schedule views to look like that:

Obviously we're styling things differently, but what they really want is the track icons to display in the exposed filter and alongside the individual sessions.

**Individual Sessions** We have a content type called session, and a taxonomy called track. The taxonomy has an image field called track icon (field\_track\_icon), and there's a term reference field on the session that holds the selected track.

I managed to get the icons to display in the view with the sessions:

View setup -

Preview -

But I need to do some conditional processing - if the field "field\_hide\_track" on the individual session is true, then don't display track icons (or the value of field\_hide\_track, obviously.) We have a certain session type that needs to contain all of the choices from the taxonomy (i.e. be associated with all tracks) but do not want it to have a visual indicator. Right now, because they have all the choices, the view displays all of the icons from the taxonomy. It also displays the icon twice if there are multiple speakers, but I think that's because of the way we have things grouped. Basically we want the icon to display before the session number/title line for all sessions that don't have field\_hide\_track checked.

I've tried custom templates (views-view-fields--at-a-glance-test--page.tpl.php and views-view-field--at-a-glance-test--page.tpl.php, where the view's machine name is at\_a\_glance\_test), but can't figure out how to get the information I need to do the conditional processing. Can someone point me in the right direction?

**Exposed filter** I have no idea where to start with this one. We're using Better Exposed Filters module to allow checkboxes instead of dropdowns, etc. I already have a views-exposed-form template to handle the background color and font choices, etc. but aside from some kind of horrible hard-coding, I don't know how to get the icons from the taxonomy to display next to the checkboxes. I think I could probably move the css for this into the template file and generate a background property for each taxonomy term that would include the image, but I don't know how to get the image from the taxonomy term field in the context of the views-exposed-form template.

**EDIT to add Views PHP code that worked**

```
<?php
if(isset($data->field_field_hide_track[0]['raw']['value'])) {
    if($data->field_field_hide_track[0]['raw']['value'] == '0') {

    $image_vars = array(
        'path' => file_create_url($data->field_field_track_icon[0]["rendered"]["#item"]["uri"]),
        'alt' => $data->field_field_track_icon[0]["rendered"]["#item"]["alt"],
        'attributes' => array(
          'class' => array('session_list_track_logo')
        )
      );

    $track_logo = theme('image', $image_vars);
    print "<h3>" . $track_logo . " " . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "</h3>";
    }
    else {
      print "<h3>" . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "</h3>";
    }
}

?>

```

# Answer
> 0 votes
1. To show fields you have to use views\_php where you can check

if ($row-\>field\_hide\_track) { print $row-\>field\_track\_icon; }
2. For filters you are on the right track you are showing terms as checkboxes you just have to style labels of the field just like DrupalCon Denver's site something like this.

# views-exposed-form-schedule-page .form-item-edit-track-1 label, #views-exposed-form-schedule-page-1 .form-item-edit-track-1 label, #views-exposed-form-schedule-page-2 .form-item-edit-track-1 label {

background: url(/sites/all/themes/denver2012/images/track-1.png) 0 0 no-repeat; }

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


title: Taking over an existing Drupal site

text:
# Question
Title: Taking over an existing Drupal site
On ServerFault, this question "Ending company IT Admin relationship" has a pretty good general checklist for taking over an existing IT system, but I'm wondering as it relates to Drupal:

* What system access controls should I get, or confirm have been changed after the takeover?
* What is the most effective way to assess the scope of existing custom configurations, development, etc done?

If it matters, the existing site is on Drupal 6, but talking about porting the site from 6 to 7 is beyond the scope of this question.

# Answer
> 2 votes
To save yourself access headaches:

1. Get credentials for the "user 1" account that has full Drupal access
2. Get database access or a copy of the most recent database
3. Get SSH Access to the production server

To audit the site once you get access:

1. Install http://drupal.org/project/hacked to make sure there haven't been any undocumented changes to Drupal core or contrib modules.
2. Look in /sites/all/modules/custom to find any custom modules. If nothing is there one good way to tell if you're missing any hidden ones is by looking at http://example.com/admin/build/modules and looking for modules without a version number. They may be hiding in /modules or /sites/\*site\_name\*/modules.
3. Have a look at the theme and especially the contents of template.php. Often times a site will have a lot of modifications happening here.
4. After looking at the items found in #1, #2 and #3 you shouldn't expect to have found a whole lot. The custom modules should be mostly hook implementations and 'glue code' not re-inventing the wheel or re-creating functionality found in popular contrib modules but your mileage will vary here depending on how custom the site requirements originally were.

# Answer
> 1 votes
To the first part:

1. All access to the actual server. This may mean RDP, SSH, or other login methods, and will depend on the server and its operating system.
2. Database administration privileges. If the server cannot be reached from outside of the system, as is most common, then server access will take care of this, but checking which accounts has high privileges on the database is still important.
3. The admin, or "User 1", account on the Drupal site itself as well as any other "high-level" users. The permissions system in Drupal isn't very fine grained, and both user 1, as well as any accounts with permissions to administer users, roles, modules and themes, are potential security problems. A well built Drupal site will have no use for the eval function and the corresponding PHP Filter module, and as such it should be turned off completely in PHP. If not, there are unfortunately a large number of ways to subvert a site, and if it is *severly* misconfigured, possibly even the server. Try disabling eval in a test environment and see if the site breaks. (Anyone further interested in this part of Drupal security should checkout http://drupal.org/sandbox/balint.kleri/1119750)

As for the second part of your question, I don't think there is any good answer, unless the previous developers has actually documented their work. This could be in code, as user stories written with a client, or just a text document in the root directory of the sites repository. Drupal allows for to many development paradigms for there to be a clear cut answer otherwise.

---
Tags: 6
---


# Question
Title: Print registration and login forms on same page
How do I print the register and login forms on the same page?

I think I am really looking just for the form IDs, but if you've got the right render function handy it would be very appreciated.

# Answer
> 12 votes
```
print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));

```

See user\_register\_form() and user\_login\_block() for details. Note that `user_register_form` is an unusual form builder function: it redirects in some cases.

# Answer
> 6 votes
I took the code from LoginToboggan. This is what I got.

```
/**
* Implementation of hook_theme()
*/
function os_pages_theme() {
  return array(
    'os_pages_login_form' => array(
      'variables' => array(
        'register_form' => NULL,
        'login_form' => NULL,
      ),
    ),
  );
}
/**
* Logintobbogin provides the code to consolidate
* the registration page and the login page however
* it doesn't do exactly the way we want so we will
* take the code.
* @see http://drupal.org/project/logintoboggan
*/

 /**
 * Implementation of hook_menu_alter().
 */
function os_pages_menu_alter(&$callbacks) {
  // Kill the tabs on the login pages.
  $callbacks['user/login']['type'] = MENU_NORMAL_ITEM;
  $callbacks['user/login']['page callback'] = 'os_pages_login_page';
  $callbacks['user/register']['type'] = MENU_CALLBACK;
  $callbacks['user/register']['page callback'] = 'os_pages_login_page';
  $callbacks['user/register']['page arguments'] = array('register');
  $callbacks['user/password']['type'] = MENU_CALLBACK;
  $callbacks['user']['page callback'] = 'os_pages_login_page';
}
/**
 * Menu callback for user/login
 *   creates a unified login/registration form (without tabs)
 */
function os_pages_login_page() {
  global $user;
  if ($user->uid) {
    menu_set_active_item('user/' . $user->uid);
    return menu_execute_active_handler(NULL, FALSE);
  }
  else {
    // Title just clutters the interface...
    drupal_set_title('');
    $output = os_pages_login_form();
    return $output;
  }
}
/**
 * Builds a unified login form.
 */
function os_pages_login_form() {
  $register_form = drupal_get_form('user_register_form');
  $login_form = drupal_get_form('user_login');
  $rendered_register_form = drupal_render($register_form);
  $rendered_login_form = drupal_render($login_form);
  $variables = array(
    'login_form' => $rendered_login_form,
    'register_form' => $rendered_register_form,
  );
  $output = theme('os_pages_login_form', $variables);
  return $output;
}
/**
 * Theme function for unified login page.
 */
function theme_os_pages_login_form($variables) {

  $register_form = $variables['register_form'];
  $login_form = $variables['login_form'];
  $output = '';

  $output .= '<div class="login-form">';

  // Add the login and registration forms in.
  $output .= '<div id="register-form">' . $register_form . '</div>';
  $output .= '<div id="login-form">' . $login_form . '</div>';

  $output .= '</div>';

  return $output;
}

```

# Answer
> 4 votes
LoginToboggan do this for you: Install it, and go to admin/config/system/logintoboggan; select "Present a unified login/registration page."

# Answer
> 4 votes
For this You need to create a page for Registration like this

```
page-user-register.tpl.php

```

And print the page contents as usual. in that page you could try render `user_login_block`

Additional resources

1. http://www.trevorsimonton.com/blog/page-usertplphp-profile-php-template-drupal
2. http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_login\_block/7

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


# Question
Title: How do I create a view to re-arrange blocks or menu items?
I would like to create an admin view that allows to reorder menu items. I know it is a standard admin feature, but I would like to display it in a panel.

How can I do that ?

# Answer
> 0 votes
You can use draggableviews to reorder the items.

---
Tags: views, routes
---


# Question
Title: create list of  content titles at end of each articles
I want create block, view first articles as full node and others just view titles at the end of first articles.

for instace: when create content type like 'opinion' and show 10 articles on every page, how view first articles (newest) as full node and 9 articles just view titles.

I used drupal 6

Best Regards

# Answer
Create a views display in which you'll show complete node and add an attachment to display which'll show the titles of all the other nodes.
> 0 votes

---
Tags: views, blocks
---


title: How can I redirect the user to my view?

text:
# Question
Title: How can I redirect the user to my view?
I made a view ("exampleview") that needs an argument: myarg. I can load my page at "exampleview/myarg" and at "exampleview".

When I call `drupal_goto(exampleview/myarg)`, the destination is only "exampleview".

I get the same result with `$arr = array('exampleview','myarg');`.

Can anybody help me?

# Answer
> 1 votes
This is from drupal\_goto

> Usually the redirected URL is constructed from this function's input parameters. However you may override that behavior by setting a destination in either the $\_REQUEST-array (i.e. by using the query string of an URI) This is used to direct the user back to the proper page after completing a form. For example, after editing a post on the 'admin/content'-page or after having logged on using the 'user login'-block in a sidebar. The function drupal\_get\_destination() can be used to help set the destination URL.

It seems like your destination parameter is set so you have to clear destination parameter or use header function

---
Tags: views, uri
---


title: Dynamic field title D7

text:
# Question
Title: Dynamic field title D7
Basically I want to be able to have a user be able to specify a title for a long text and summary field. Functionality being that you could have this with only one field:

day 1: doing something this is what we did on day 1

day 2: doing something on day 2 this is what we did on day 2

Basically I want one field input for my content type creation form that correlates a title and the paragraph to go with it. I thought of a shoddy way to do it by creating a separate content type and bringing in the copy with a views block but I feel like there should be a much simpler way to allow a user to input a title to attach to a long text and summary field.

# Answer
> 1 votes
Not sure, but this sounds like it could be a job for the Field Collection module.

---
Tags: 7, entities
---


# Question
Title: How to invoke a search api from drupal site for Ubuntu Unity lense?
I'm creating a simple Unity lense for my college site which is based on Drupal, but I don't know how to adapt this command for Drupal API. Please help, it's python.

> We now create our query url, using the Wikipedia opensearch API url = ("%s/w/api.php?action=opensearch&limit=25&format=json&search=%s" % (self.wiki, search))

I'm using template to write lense following Wikipedia example http://developer.ubuntu.com/2012/04/how-to-create-a-wikipedia-unity-lens-for-ubuntu/. I don't know python but Im familiar with C. This Drupal API calling is the only problem I have to successfully develop a lense. Please help!

# Answer
> 2 votes
Your site is running Drupal 6.26 http://en.ict.edu.rs/CHANGELOG.txt

The Unity Lense does not require OpenSearch. You essentially just need to Curl your search results page with a querystring and parse out the search result links.

Eg, send a Curl request with: http://en.ict.edu.rs/search/node/example

You could show some answers easily that way for any drupal site. You could setup a custom View for searching your content as well if you wanted, or even install the Services module and make a small dedicated search api.

I'm actually running Ubuntu 12.04 here and installed the Lense stuff which looks neat -- but I'm too busy to code up a small example, sorry. Hopefully these thoughts will point you in the right direction.

EDIT: alot of the code is really there already when you start your Lense project. You just need to tear through the results from /search/node/KEYWORDS\_HERE you get from the request in Python ...

---
Tags: search
---


title: Drupal Redirect User Login Page

text:
# Question
Title: Drupal Redirect User Login Page
Basically I need to redirect this page

```
http://website/?q=user
to
https://website/?q=user

```

I tried adding a redirect rule to the .htaccess file in /var/www/html/ but that didn't work. From what I know ?q=user is more of an argument then a page. How can I achieve this?

Any help would be greatly appreciated.

# Answer
You might want to have a look a the Secure Pages module, which is:

> A small process which will redirect the required pages to a SSL version of the page.

You can easily set up the `user/login` path as an SSL-required page, and the redirect will be handled for you.

If you want to do it manually, a rule like this in .htaccess would probably work:

```
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^user$ https://%{SERVER_NAME}/user [R=301,L]

```

That would need to go above Drupal's main rewrite rule for index.php.

It's worth bearing in mind you'll need to do this for the `user/login` path as well as that can be accessed directly.
> 1 votes

# Answer
You can achieve this using Rules and make a rule that when going to that page to redirect the user to the https: page.

http://drupal.org/project/rules
> 1 votes

---
Tags: redirection, users, .htaccess
---


# Question
Title: Why does jQuery slideToggle revert back to initial hidden state after running?
I have a Superfish menu and a simple jquery slideToggle animation attached to each menu item. I am using Drupal 7 & the Superfish module.

The idea is that on click it will show the body content of the site which is initially being hidden. All seems to work fine the click event fires the toggle but after the animation is done, it quickly reversed the animation back to the initial hidden state.

Doing this is seems pretty trivial with straight HTML / jQuery. But it's not quite working within my Drupal theme.

Here is my jQuery:

```
(function ($) {
Drupal.behaviors.my_fusion_menu = {
attach: function(context,settings) {

$('#content').hide();
$('.sf-depth-1 a' || '.sf-depth-2 a' ).bind(
    'click', function() {$('#content').slideToggle('slow');}
     ) // /click
    }   // /attach
}; // /Drupal Behaviors
})(jQuery);

```

I am fairly new to working with jQuery. It seems like the answer is pretty simple, but I am not sure how to set this up.

Any suggestions?

# Answer
Try this code below.

```
$('#content').hide();
$('.sf-depth-1 a' || '.sf-depth-2 a' ).click(function() {
  $('#content').toggle('slow', function() {
    // Animation complete.
  });
});

```
> 0 votes

---
Tags: 7, javascript, navigation
---


# Question
Title: Check if logo, sitename, slogan, and secondary links exist
How do you check if logo/sitename/slogan & secondary links are enabled from within a function? (outside of preprocess\_page)

This seems to work for logo:

```
$logo = theme_get_setting('logo');
if (empty($logo)) {
...
}

```

but this doesn't for secondary links:

```
$secondary_links = theme_get_setting('toggle_secondary_links');
if (empty($secondary_link)) {
...
}

```

# Answer
`$secondary_links = theme_get_setting('toggle_secondary_links');` is working fine.

It doesn't work if secondary menu is disabled form `admin/appearance/settings`

It works when secondary menu is disabled form `admin/appearance/settings/theme-name`

OR

It works when secondary menu is disabled form `admin/structure/menu/settings` source of **Source for the Secondary links** is set to 'No Secondary links'
> 1 votes

---
Tags: 7
---


title: How to access a website database?

text:
# Question
Title: How to access a website database?
Firstly I'm extreamly new to drupal and right now I was given a task to edit a currently online published website. The old designer didn't left me with any idea but from what I was told, the website uses Drupal to operate. I'm more to the classical way of building a website, for example: I create the scripts and upload it to a server and the server published it online. So how do I acess the website's database to make all the necessary changes to the scripts?

Thanks in advance.

# Answer
> 1 votes
The short answer: you don't generally access the database in Drupal. Drupal serves as an intermediary between you and the database, and if you access the database directly more than likely you are going to cause yourself many problems in the long run, especially in the beginning when you're not very familiar with Drupal.

For more, see Understanding Drupal and the Structure Guide on Drupal.org.

# Answer
> 1 votes
Generally you do not want to access the database without using Drupals functions to do so. With that being said you can create modules that will do that work for you. This can cause issues if you try to access and manipulate data from the database without using drupal functions to do it for youu.

# Answer
> 1 votes
Welcome to Drupal world! :D

First what are you trying to achieve? Do you want to update the Drupal code? Before touching prod make sure you have a backup of the latest db and code. You must be aware of the golden rule "don't hack the core". Drupal uses API(hook) in extending Drupal functionality.

It's not a good practice to do the development directly on live. If you want to update database in live for some reason, use hook\_update\_N and run in live once deploy.

Hope this help.

---
Tags: 7
---


title: how to add directory name after uri

text:
# Question
Title: how to add directory name after uri
I want to append the name of a directory, say 'abc' to `public://` uri of `sites/default/files` directory, such that it will point to the 'abc' directory inside `sites/default/files`.

Actually, whenever I try to do this `file_move($file_object, 'public://abc', FILE_EXISTS_REPLACE)` it moves the file inside `sites/default/files` and creates a file called 'abc'.

I want to move the file inside 'abc' directory, by appending 'abc' to `public://`, how do I do this?

I have searched for this and found that `public://abc` does the trick, but its not working for me.

# Answer
> 4 votes
Your function is telling drupal to move $file-\>filename to public://abc and hence renamed to abc. Drupal is doing what you are asking to do.

your $destination should be - 'public://abc/' . $file-\>filename

file\_move($file, $destination, FILE\_EXIST\_REPLACE );

Below code should work (though not tested):

```
 $file = file_load($fid);
 $destination = 'public://abc/';
 if(file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
   file_move($file, $destination . $file->filename, FILE_EXIST_REPLACE);
 }

```

---
Tags: 7, files, uri
---


# Question
Title: Error while loading / saving taxonomy term on external DB
I have 2 different Drupal bootstraps with shared DB, and I'm switching from the "slave" bootstrap with db\_set\_active('shared') when need to work with the shared DB.

example:

```
function test_function(){
  db_set_active('shared');
  $term_tid = array_keys(taxonomy_get_term_by_name($term, $vocabulary = 'vocab'));
  if (!$term_tid){
   $term = new stdClass();
   $term->name = $term;
   $term->vid = 1;
   taxonomy_term_save($term);
  }
  db_set_active('default');
}

```

while using either one of the taxonomy functions, taxonomy\_get\_term\_by\_name or taxonomy\_term\_save giving me this error:

> PHP Fatal error: Class name must be a valid object or a string in /home/user/www/includes/common.inc on line 7618

any help appriciated!

# Answer
> 0 votes
SOLVED! after long head bashing, what fixed this for me was to manually empty the "cache" tables with PMA on the "shared" DB!

important to notice that Drupal native Clear Caches didn't do the work, it had to be removed from the DB!

---
Tags: taxonomy-terms, database
---


# Question
Title: How to add the admin role to Drupal 7 after upgrading from Drupal 6?
In Drupal 6 there was a module called Admin Role which allows you to make a superadmin role (same rights as superuser). This function is now in core (as of Drupal 7). So if you install Drupal 7, you get three roles by default: anonymous, authenticated, administrator.

However, when upgrading a site from D6 to D7, this new admin role is missing. How do I add this role or convert an existing custom role to be the admin role?

# Answer
You can set an admin role in `admin/config/people/accounts` or by going to Configuration -\> Account Settings under "People" label.

The help text under the select box says:

> This role will be automatically assigned new permissions whenever a module is enabled. Changing this setting will not affect existing permissions.

So remember to assign the existing permissions to this new role! But whenever a module is enabled and new permissions are created, this role will automatically be granted those.

To create new roles you go to People -\> Permissions (tab) -\> Roles (secondary tab)
> 3 votes

# Answer
Just create a role that you want to be your second admin role, and then assign it as `admin/config/people/accounts`.

> This role will be automatically assigned new permissions whenever a module is enabled. Changing this setting will not affect existing permissions.
> 2 votes

---
Tags: updating, users
---


# Question
Title: Can one feature module make additions to another feature module?
I would like to have two feature modules for users to enable. One basic and one advanced. For example, the basic feature creates a blog content type, with only title and body fields. The advanced module, once enabled adds additional fields to that original content type, such as tagging or imagefield. Is this possible or will one override the other? Or will my site blow up? or?

# Answer
> 3 votes
It's definitely possible, I had to do something similar yesterday and I'm happy to say features can handle it perfectly.

The trick is that your 'advanced' feature will not contain the content type at all, but simply a list of the extra fields that are attached to the content type defined by the original rule.

When you install/enable the second feature module, the extra fields will be added to the existing content type as if by magic. I was pleasantly surprised at how well this works.

There is an example of a well established Drupal distribution using this same method (it's where I got the idea if I'm being honest); OpenPublish contains the `openpublish_article` feature, which defines a content type, and the `openpublish_atricle_extra_media` feature, whose sole job is to add a couple of extra fields to the article.

Just as a side note, it would probably be a good idea to make your main feature module a dependancy of the second, so the content type is definitely defined by the time the second feature is trying to add the extra fields to it.

# Answer
> 0 votes
You can easily do this by using hook\_form\_alter

```

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_FORM_ID') {
    // Write your code here with conditions.
    global $user;
    if($user->role == 'somerole') {
      // Here You can add form fields whatever you want for somerole.
    }
    else {
      // Here You can add form fields whatever you want for other roles.
    }
  }
}

```

But for fields which you want to add for a specific role should not be required field.

---
Tags: 7, features
---


# Question
Title: How to create a single page using Drupal Commerce containing product, billing infor payment method?
I'm trying to create a donation form as product, but I want the billing information/Account Information form and Payment method options to be in a single page together instead of having them on a different process page.

Is this possible?

Is there a way to configure this in Drupal Commerce or is there a programmatic way to do this?

# Answer
> 2 votes
The checkout flow uses panes, and there is nothing hindering you to put all of the panes in a single page and skip the review page if you wanted to. This can be setup in the checkout settings with a simple drag and drop interface. Should be fairly simple to setup the way you want to out of the box.

---
Tags: commerce
---


# Question
Title: Commerce product fields as optional attributes
I'm trying to create some kind of product attributes by adding fields in manage fields in Store | Product types. Is there any solution to give product creator ability to select which fields he want to use when adding product. Creating product types containing all possible situations would be strange. Example: I create one customizable product, but I want to give it 4 various attributes. For another creating product I could select checkboxes for different attributes.

# Answer
You probably want to group products that a similar into the same product types and setup different product types, instead of having a single multipurpose product type that can be turned into anything. The product creator can decide which fields to use by choosing which product type to use. A distinction that will come very naturally for non technical people.
> 1 votes

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


# Question
Title: Field for additional charge the drupal / drupal commerce way
What is the canonical drupal commerce way of storing data for say something like an additional charge?

Would it be a price field / text field / Line item field?

I would like the field to store data like this:

label: color charges desc: field stores the additional amount for a color foobar product number of values: 1

example value: 0.75

# Answer
> 0 votes
You don't make the use case very clear, but sounds like you could use some of the existing price fields, fx unit price on product line items, but simple add the price with a custom component. That way the price would be viewable in the order overview, but when seeing the product cost you get the simple and correct value of $ x.xx.

---
Tags: entities, commerce
---


title: Drupal 7 subfolder multisite

text:
# Question
Title: Drupal 7 subfolder multisite
I'm trying to setup a drupal 7 multisite using subfolders for example:

example.com/site1

example.com/site2

In my drupal sites folder I have sites1 and sites2 according to sites.php I should be able to set it up as the following:

```
$sites['example.com/site1'] = 'site1';
$sites['example.com/site2'] = 'site2';

```

However this doesn't work, I can definitely see a site at example.com but am unable to see any of the sites in the sub folder.

# Answer
> 6 votes
If you want to do it this way then you have to symlink the folder to the root of the drupal install:

```
cd /var/www/drupal
ln -s . site1

```

Then within sites.php use the following:

```
$sites = array(
    "example.com.site1" => "site1",
);

```

---
Tags: 7, multi-sites
---


# Question
Title: How know what theme/theme name a Drupal site is using?
Like in Wordpress, we can know what theme name a site is using by look at the page source and it will show something like

```
wp-content/theme/theme-name

```

Well, how we can know what theme a Drupal site is using? I try to look at the page source of a Drupal site but i cannot figure out what theme or theme name the site is using.

Is there any trick to unlock this?

# Answer
You can get it from source of any page. Have a look for the javascript array at the top/bottom of the page that begins with:

```
jQuery.extend(Drupal.settings, {...

```

There's a setting in that array called "theme" which contains the name of the theme being used for that page.
> 8 votes

# Answer
Very similar in Drupal (by default).

Look for

> /sites/default/themes/THEMENAME

or

> /sites/all/themes/THEMENAME

But there are ways to rename / remap those standard folders to hide singns for Drupal.
> 1 votes

# Answer
Just right-click on the drupal logo image or any Drupal site's logo image that appears at the top, and select "Inspect element". In the src of the image the name following "themes/" is the name of current theme; e.g. `http://sitename.com/themes/bartik/logo.png` then bartik is the current theme.
> -1 votes

---
Tags: theming
---


title: How to change my base URL

text:
# Question
Title: How to change my base URL
I have built a website using drupal. Now, the base URL is http://xxx.xxx.xxx.xxx/drupal. But I want to change base URL as http://xxx.xxx.xxx.xxx How do I do?

Thanks.

# Answer
go to `yousite/sites/default` and open the `settings.php` file and find `$base_url` and change it to the new value (somewhere around line 270).

**NOTE :** `settings.php` is a read-only file, you need to clear the read-only flag first to make the changes. You'll need to restart the server to update the changes.
> 12 votes

# Answer
There is a global variable called `$base_url` that you can set in sites/default/settings.php. Try changing its value.
> 5 votes

---
Tags: uri
---


title: Create a menu pointing to #

text:
# Question
Title: Create a menu pointing to #
Using menu token I have created a menu as shown in figure

I also have sub-menu items for this menu. Whenever the user clicks on this menu, the page is being refreshed (which is the obvious behavior), but I don't want any sort of action on the menu. In simple HTML we can do my simply using `href="#"`, but Drupal is not allowing to set the Path of the menu to `#`. Is there a way to do it?
I also tried Menu attributes to do it, but I seem to be missing something.

# Answer
Yes drupal doesn't suppport # in menu\_links, You might get some clues here - http://drupal.org/node/325533
> 2 votes

---
Tags: routes, 7
---


# Question
Title: How to effectively manage a site with Drush make?
What things are important to consider when managing a site using Drush make?

# Answer
"Make files", in the Drush and Drupal context, define a set of modules, themes and libraries that make up a site. While one could stick the entire sites/all/modules directory into git, the make file is a lot faster to handle, both for git and the developers. Below is a make file from an actual project of mine. I've cut out a lot as the whole file is hundreds of lines, but I've retained enough to show all of the functionality I've used.

```
; API
api = 2

; Core
core = 7.x
projects[drupal][version] = 7.14

; Contrib modules
projects[date][version] = 2.0-alpha4
projects[email][version] = 1.0

; Media and file_entity go hand in hand - please make sure they work together.
projects[media][version] = 2.0-unstable5
projects[file_entity][version] = 2.0-unstable5

; Cron modules
projects[ultimate_cron][version] = 1.6
projects[background_process][version] = 1.12

; Performance modules
projects[expire][version] = 1.0-alpha2
projects[cache_actions][version] = 2.0-alpha3

; Unstable modules
projects[menu_node_views][type] = module
projects[menu_node_views][download][type] = git
projects[menu_node_views][download][url] = http://git.drupal.org/project/menu_node_views.git
projects[menu_node_views][download][revision] = f46dd41eb8c4e693a6642a6c461afa57d99a6f1b

projects[filefield_sources_plupload][type] = module
projects[filefield_sources_plupload][download][type] = git
projects[filefield_sources_plupload][download][url] = http://git.drupal.org/project/filefield_sources_plupload.git
projects[filefield_sources_plupload][download][revision] = da374770b80fcbc0dab17158d38c8436ef29caca

projects[menu_token][type] = module
projects[menu_token][download][type] = git
projects[menu_token][download][url] = http://git.drupal.org/project/menu_token.git
projects[menu_token][download][revision] = 8c18fbb

; Libraries
libraries[mediaelement][download][type] = "file"
libraries[mediaelement][download][url] = "https://github.com/johndyer/mediaelement/zipball/2.7.0"

; Patches

; #1491150: node_load in menu_node_menu_link_insert is not safe - http://drupal.org/node/1491150
projects[menu_node][patch][] = http://drupal.org/files/menu_node-node_load-in-menu_node_menu_link_insert-1491150-1.patch

; Fix rendering of relation endpoints
projects[relation][patch][] = http://drupal.org/files/relation_table_endpoints_break.patch
projects[relation][patch][] = http://drupal.org/files/relation_bundle_permissions.patch

libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][destination] = "libraries/jquery-json"

```

The api line defines which Drush make API to use for the rest of the file. One important thing to notice about the file, is that all modules either have a specific version, or point to a specific git commmit. We *never* have -dev versions in our files. When we show up at a client meeting, or hand over the make file to the Jenkins server, there must *never* be any surprises. The exact version included in the file should be tested and expected to pass all types of tests. This is important to be able to delivery something of high quality.

In my company, the general agreement is that every team provides a shell-script called "build", in the root of the repository, which is responsible for setting up the site, so that automated tests can be run by the same cross-team CI setup.

Module updates can be done quickly directly on sites for testing, but officially by updating the make file, and rebuilding the site.

My team currently uses this set of build-scripts. I'm working towards moving much of the functionality into a drush extension that will heavily use provision though. A CLI version of Aegir if you will.
> 28 votes

---
Tags: drush
---


title: How to translate views footer content?

text:
# Question
Title: How to translate views footer content?
I am building a multilingual site using Drupal 7. I have used Views to generate a page, and in that page I have added a link in the view footer. The custom code that I use in my views footer is as below.

```
<?php <a href ="/blog-archieve">To blog archive</a>

```

My problem is that I am using i18n module to translate the contents. In the translate interface I get the full above code, and as a result I lose my footer in views. Is there any way by which I can translate the "To blog archive" instead of the full code?

# Answer
> 2 votes
Try changing your footer to the following:

```
<?php
$link = l(t('To blog archive'), 'blog-archive');

print $link;
?>

```

References:

`l();`

`t();`

# Answer
> 1 votes
If you want to avoid using the php filter and are ok with having the different translations all together, then you can use Language Sections. It uses a format like this:

> === es ===
>
> This text will only be displayed when Spanish language is selected by the user.
>
> === fr ===
>
> This text will only be displayed when French language is selected by the user.
>
> === others ===
>
> This part will be displayed when the user's selected language is neither Spanish nor French, i.e. all other languages, and so might provide text in a common language such as English.
>
> === all ===
>
> This part will be displayed for all languages.

You can also use Internationalization Views. It doesn't have a stable release for 7.x, but it does have over 4k sites reporting they're using the 7.x dev release.

(I'm afraid I have no personal experience with either.)

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


# Question
Title: Manage display not updating user account display
This is a new D7.14 site started only 3 days ago. There is no use of organic groups in this site. I added several fields (i.e. First Name, Last Name, City, State, Zip - as text and list fields). I set these to show on user registration form and to display publicly. I came back about a day later and changed the display settings on User Account to hide the labels and to change the display order. I also hid one of the fields completely on User Account. I opened a new browser and navigated to the user account for a random user - the labels still appear and the order has not been updated. I cleared cache - no difference. I ran cron - no difference. I subsequently updated a few modules and had to run update.php - no difference.

Any suggestions?

# Answer
> 1 votes
Are you sure you edited the right viewmode? Have a look at the viewmodes which are enabled. Probably you moved the fields not on the viewmode "Full Content" (or "Full Profile") but on the "Default" instead. Or maybe the "Full Profile" is not activated?

---
Tags: entities
---


title: Table and Form in the same page

text:
# Question
Title: Table and Form in the same page
I have a quick question. I work with a form that consists of the following:

```
$form['data_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Killer search engine!'),
    '#id'   => 'killer-search-engine',
    '#maxlength' => 1024,
    '#description' => t('Search by using tags and free text'),
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Go!!',
);
...
...
fill $table
...
...
if(sizeof($form_state['input'])!=0) {

    $form['table'] = array (
        '#title' => 'TABLE',
        '#type'   => 'table',
        '#value' => $table,
    );
}
return $form.

```

The form is appearing but the table element of it, even though it is filled with html code of an actual table(I checked through dpm($form)) does not appear. Anyone with a quick fix?

Thanks beforehand

# Answer
> 4 votes
If you want to display the values in table format you can use Table theme
Example:-

```
$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
  );

```

`$header` and `$rows` would be arrays.

---
Tags: forms, theming
---


# Question
Title: How can I use the Comment field as a way to privately message the node author?
I am working on a classifieds site where individual users can sign up and, of course, post things they would like to sell.

However, I need for users, both anonymous and signed up, to be able to contact the poster about his or her item.

Using the default comment form for this would be perfect. What would I need to do in order to allow only the author of that node to see the comments for his node? I don't mind writing a module if I need to, but I am not sure how to get started. Even if I had to go that route, sounds like I would need to modify the permissions setting?

I know there are other modules out there like Private Message, but that's just too big and bulky when Comments work almost exactly like I need them to.

Thanks!

# Answer
> 1 votes
So you want to use the comment form to do something other than leave comments on an article? That's pretty much the sole reason the comment form exists.

The core Contact module allows you to enable contact forms for every user on a site which, when used, send the message as an email to the corresponding user. I suggest you enable that module, then use something like hook\_node\_view() to add the contact form for the node author to the bottom of a node when it's displayed. I think that approach makes a good deal more sense than trying to use the comment form to do something it's not intended to do.

# Answer
> 1 votes
I see some potential pitfalls with this approach:

1. It probably won't be quite as simple as you describe because I guess you'd also like commenters to be able to see their comments, and replies to their comments, while hiding other people's comments. (Or am I wrong?)
2. You mention you'd like to allow anon users to comment, so you need some way to differentiate one anon user from another (if they're able to see their own comments, but not others).
3. It won't play nicely with page caching (at least without a bit of effort).
4. It might make life a bit more difficult if you want to have normal comments on a content type at some point. (Eg. should the comment moderation tools be showing comments which are actually private messages?)

If you do want to go down this route however you can use `hook_node_view_alter()`.

---
Tags: 7, comments
---


# Question
Title: How to build and organize menus with rich taxonomies and complex view-based menus
I would like to hear your insights about strategies on organizing menus. I mean two main approaches: having each menu header as an individual Drupal menu vs. having all menus grouped as one big menu, perhaps named "Main menu".

I built quite a large site where I had to use such modules as OM Maximenu, Taxonomy menu/Taxonomy menu trails, Menu Block, Sitemap, DHTML Menu. Without much knowledge about Drupal and the consequences of my choice, just to keep my progress on, I took my liberty to sometimes put a group of menu items as individual menus, sometimes I grouped them together (this was the case of Taxonomy menu and Menu Block where I could define the level at which menu starts).

Then, when I installed Sitemap I saw that my menu organization revealed to public. This was also a lesson.

Although everything works OK, I don't feel alright with this kind of mess. Especially, after some time I know I will have to do a repetitive research on how a particular menu is built, rather than have it intuitively solved right away.

**My question**: What is your preferred way to build and organize menus with rich taxonomies and complex view-based menus (OM Maximenu)?

# Answer
Typically, we put all of the site sections in the main menu.

Each site section will get its own Drupal menu. How items get into menus varies widely project-to-project, but we will rely on path-alias define section organization as much as possible.

Each section will have its own Panels pages, where the site section gets used as the context / selection rule (typically by path matching), and the menu is placed in a content area.

Occasionally, we will have a site section taxonomy, which gets used inside a custom block to display the proper menu.
> 2 votes

---
Tags: views, taxonomy-terms, routes
---


title: Excluding specific user role from query

text:
# Question
Title: Excluding specific user role from query
I have this query, which fetches all users with the role #7.

```
$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';

$result = db_query($query, array(':rids' => array(7)));

```

Some users currently have both roles #7 and #8. I beleive they are all fetched by this query. I would like to exclude users with the role #8.

Can someone help me?

# Answer
I found it.

```
$query = 'SELECT DISTINCT(ur.uid) FROM `users_roles` AS ur
WHERE ur.rid = (:rids) AND ur.uid
NOT IN (SELECT uid FROM `users_roles` WHERE rid = (:rids2))';

$result = db_query($query, array(':rids' => 7, ':rids2' => 8));

```
> 0 votes

# Answer
Try

```
$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids) AND ur.rid NOT IN (:rids2)';

$result = db_query($query, array(':rids' => array(7), ':rids2' => array(8)));

```

Or if you wanted just the more specific version

```
$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid = (:rids) AND ur.rid != (:rids2)';

$result = db_query($query, array(':rids' => 7, ':rids2' => 8));

```
> 1 votes

---
Tags: database, users
---


# Question
Title: Problem creating a node with custom PHP code
I wrote the following custom PHP code to create a node

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

global $user;
$title1=$node->title;
$node = new stdClass;
$node->type = 'Campaign_PlayerList';
$node->title = $title1;
$node->uid = $user->uid;
$node->language='und';
$node->field_cmp_playerid['und'][0]['value']=$user->uid;
$node->field_cmp_userscore['und'][0]['value']=1;
$node->field_cmp_usersupport['und'][0]['value']=1;
node_object_prepare($node);
node_save($node);
?>

```

The values for `field_cmp_playerid` and `field_cmp_attend_time` are not saved.

```
$node->field_cmp_playerid['und'][0]['value']=$user->uid;

```

doesnt work and `field_cmp_attend_time` is the same too.

What could the problem be?

Here is a screenshot of the field management form for the Campaign Playerlist content type:

# Answer
It looks from your image like `field_cmp_playerid` is a user reference field, which means the column name won't be `value`, it will be `uid`. Try this code:

```
$node->field_cmp_playerid[LANGUAGE_NONE][0]['uid'] = $user->uid;

```

The `field_cmp_attend_time` field probably isn't getting saved because it's missing from your code. It's just a date field so the column name will be `value`. If the date field you're using is a UNIX timestamp type, for example, the code would look like this:

```
$node-> field_cmp_playerid[LANGUAGE_NONE][0]['value'] = REQUEST_TIME;

```

Just in case you want to update your `field_cmp_id` as well, it's a node reference so the column name becomes `nid`:

```
$node->field_cmp_id[LANGUAGE_NONE][0]['nid'] = $nid;

```
> 1 votes

---
Tags: nodes
---


# Question
Title: How do I print custom html in nodes of a certain type using template.php?
I want to print some custom html inside nodes of a certain type. I could use node.tpl.php, but i'd prefer a template.php solution.

THX in advance.

# Answer
> 2 votes
If you want to provide a new variable to your node template file you should implement `hook_preprocess_node()` in your theme and pass it from there:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'node_type') {
    $vars['extra_html'] = my_function_to_build_html_string();
  }
}

```

Then in your node.tpl.php file you can output that HTML wherever you want like so:

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

```

If you just want to add some HTML into the normal content of the node, you would do it like this:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'node_type') {
    $vars['content']['extra_html'] = array(
      '#markup' => my_function_to_build_html_string(),
      '#weight' => -10 // Control the display order of this element
    );
  }
}

```

In either case you'll need to clear Drupal's caches once you've implemented this hook so the theme registry picks it up.

---
Tags: 7, theming
---


# Question
Title: How can I add custom field validation for one of the fields "within" an addressfield?
I'm attempting to implement one of the answers to this question on validating whether there no double-byte characters present.

Here is what I've done so far in my custom module:

```
function CUSTOMMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'profile_gen_node_form') {
    $form['#validate'] = 'CUSTOMMODULE_location_doublebyte_validation_handler';
  }
}

```

And then:

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

```

This is where I'm stuck. Addressfields include much more information than normal fields; they seem to be like a collection of fields. Here is a screenshot of the output of `dpm($form)`:

I want to check `strlen()` and `drupal_strlen()` of the value of the "locality" piece of my addressfield but I can't figure out how to do that.

I tried something like this:

```
if(strlen("field_gen_loc_current['und']['0']['locality_block']['locality']") !== '0') {
    form_set_error('locality', t('No double-byte input.'));
}
}

```

But, while this doesn't produce an error, it also never causes the validation to fail.

# Answer
I've just chucked a validation function into a dev site with an addressfield and you're right, it's a bit strange. It might be that the address field is marked as `#tree => TRUE`, and that's what's causing the long element key string.

Either way, it looks like you're checking the `$form` variable in your validate function, when the submitted data will actually be inside `$form_state['values']`. A couple of other minor alterations and you should be able to get it working:

```
function validation_function(&$form, &$form_state) {
  // Let's at least TRY to keep lines to 80 chars...
  $key = 'commerce_customer_profile|billing|commerce_customer_address|und|0';

  // Get the length of the
  $length = strlen($form_state['values']['addressfield'][$key]['locality']);

  if ($length != 0) {
    form_set_error('addressfield', t('No double-byte input.'));
  }
}

```

That example is based on the Commerce add customer form, so you'll need to inspect the `$form_state['values']` array in your own form to find out exactly what the `$key` variable should be but hopefully that'll give you somewhere to start.

Just a note on your use of `!==` above...be careful with that, it will force PHP to make sure the *types* of the variables are equal, as well as the value.

`strlen()` returns an integer, and `'0'` is a string, so `strlen('string') !== '0'` will always return `TRUE`, regardless of whether the values are the same.
> 1 votes

---
Tags: forms
---


# Question
Title: Drupal 7 & OpenLayers - Can see sample map under OpenLayers Admin: Preview but NOT under Views: Preview
I'm stumped and seeking some direction.

I'm seeking to create a dynamic map using OpenLayers, Drupal 7, Views and Custom Content Type. I've read all the documentation I can find and so far I've been able to:

* successfully create a content type (using "Geolocation Field" to store geodata instead of GeoField),
* create an OpenLayers Overlay in Views, and
* create a custom map (clone of Google Map example) in OpenLayers Admin.

In OpenLayers Admin I can view the sample map ('MySample Map") under OpenLayers Admin: Maps: Edit Map: Preview. This map successfully shows data points from content in the database.

However when I create a new View of format OpenLayer with style = MySample Map nothing shows - no datapoints and no map, only the title.

Any recommendations for debugging/resolving this problem? Thanks in advance.

# Answer
Openlayers is generated via JavaScript so wont display in the views admin. Save your view and check the page/block.

If it is still not working check the width of the map. Sometimes, when set to auto the map will collapse showing nothing. Set a fixed with and check again. If it works then some simple css will fix the rest.

Good luck :)
> 1 votes

---
Tags: views, javascript
---


title: "drush rr" error

text:
# Question
Title: "drush rr" error
I am trying to perform a simple `drush rr` in my drupal directory. I have been able to do this before, but all of a sudden this no longer works. I have made changes to my drupal site, but I have no idea what might be causing it.

The error is as follows:

```
chlong@chlong-Vostro-460:/var/www/drupal7$ drush rr
PHP Fatal error:  Call to undefined function lock_acquire() in /var/www/drupal7/includes/bootstrap.inc on line 3106
Drush command terminated abnormally due to an unrecoverable error.     [error]
Error: Call to undefined function lock_acquire() in
/var/www/drupal7/includes/bootstrap.inc, line 3106

```

Does anyone have any ideas on how to resolve this issue?

# Answer
> 5 votes
Newer versions of Drupal 7.x (7.13+), have added locking to the registry rebuild process. This means that the locking system now needs to be available to call that function.

drush rr specifically tries to include as less as possible, to be able to rebuild the registry before something can break.

For you, this simply means that you need to update your version of registry rebuild, as this has been fixed already.

That said, I am very much looking forward to Drupal 8, for which we are currently working hard to be able remove the registry in favor of a PSR-0 class loader that finds classes based on conventions and does not need to scan files to build up a mapping of class names to files.

# Answer
> 0 votes
It looks like your `includes/lock.inc` file has gone missing. If that's the case, you should download Drupal again.

---
Tags: 7, drush
---


# Question
Title: What is the purpose of the entity_metadata_wrapper() function, and why should I use it?
I seem to be developing add-ons to a lot of modules that use Entity API at the moment, and the `entity_metadata_wrapper()` function keeps on popping up.

The docs page says this about it:

> Returns a property wrapper for the given data.
>
> If an entity is wrapped, the wrapper can be used to retrieve further wrappers for the entitity properties.

Ignoring the wonderfully Freudian spelling of the word 'entity' in there, I don't really understand what the purpose of these wrappers is.

I understand that the function essentially returns a `EntityDrupalWrapper` class:

> The wrapper eases applying getter and setter callbacks of entity properties

But what I can't understand is *how* it makes things easier.

For example, to update the status property of a node I could use this code:

```
$node = node_load($nid);
$node->status = 1;
node_save($node);

```

That's pretty clean. As I understand it (but may be wrong) the equivalent code using `entity_metadata_wrapper()` would be more verbose than that.

I'm not sure if it's simply the use of the term 'wrapper' that's tripping me up here, but I've looked through the code in the Entity module too and I'm not really any closer to understanding it.

Is anyone able to explain what the benefits of using this function are, and perhaps provide a simple code example for a common use-case?

# Answer
> 24 votes
Yes, changing the status of a node is trivial, as that is a hardcoded property.

Fields on the other hand, are much more complicated. They are nested three levels deep, while there is field\_get\_items() to get them in the correct language, there is no such function for setting field values. So, you always need to check whether a field is translatable or not and you need know which property exactly contains the values you're looking for/want to set.

Two examples, that show what the entity wrapper can do:

* The following line adds the commerce line item to the order, taking care of the language and the actual property that holds the reference id, taken from the following answer https://drupal.stackexchange.com/a/23513/31

```
$order_wrapper->commerce_line_items[] = $line_item;

```
* In a similar way, being able to directly access a value of a field, without having to check the language, or the delta, even being able to directly access referenced entities, taken from https://drupal.stackexchange.com/a/33010/31

```
$subnode = entity_metadata_wrapper('node', $node)->field_subnode->value();
$default = $subnode->title;

```

The entity wrapper is the driving force behind flexible, powerful modules like Search API and Rules as it allows them to work their way through multiple levels of references, so that you can e.g. access a field of the product a user bought in an order with something like `[commerce-order:commerce-line-items:0:commerce-product:some-field]` (might not actually be correct, but something like that), or add the body summary of a referenced node to your search index.

That said, I'm not necessarly fond of the actual API of the wrapper, it's huge internal arrays and that even simple properties are again wrapper classes. I hope that the improved entity (and hopefully field) system in Drupal 8 will remove the need for such a wrapper thanks to having classed entities.

---
Tags: entities
---


title: Theme settings not getting saved

text:
# Question
Title: Theme settings not getting saved
I created custom settings for my theme for storing email, fb url, twitter url and g+ url. Everything is coming properly but the settings are not getting saved. I have no idea whats wrong. All the code and screenshots are below.

.info file content

```
settings[z_email] = mail@zed.com
settings[z_facebook] = fb/url
settings[z_twitter] = twitter/url
settings[z_gplus] = gplus/url

```

theme-settings.php file content

```
function z_form_system_theme_settings_alter(&$form, $form_state) {
  $form['z_email'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Email'),
    '#default_value' => theme_get_setting('mail@zealind.com'),
    '#description'   => t("Global Email Id for ZealInd site."),
  );

  $form['z_facebook'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Facebook'),
    '#default_value' => theme_get_setting(''),
    '#description'   => t("Facebook Url."),
  );

  $form['z_twitter'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Twitter'),
    '#default_value' => theme_get_setting(''),
    '#description'   => t("Twitter Url."),
  );

  $form['z_gplus'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Google+'),
    '#default_value' => theme_get_setting(''),
    '#description'   => t("Google+ Url."),
  );

}

```

The theme setting page:

# Answer
> 8 votes
You're not using `theme_get_setting()` quite right at the moment; the first argument should be the name of the setting, not a default value.

For example, your element defined as `$form['z_email']` should look like this:

```
$form['z_email'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Email'),
  '#default_value' => theme_get_setting('z_email'),
  '#description'   => t("Global Email Id for ZealInd site."),
);

```

---
Tags: 7, forms
---


title: Import CSV/XLS data to Webform?

text:
# Question
Title: Import CSV/XLS data to Webform?
Is there a way to import records into webform database from user uploaded CSV/XLS?

# Answer
This worked well for us: Webform Import

> Allows delimited data files to be imported as submission (results) into webforms.
>
> This is useful for importing submissions from other systems in to Webform. Can also be used to Edit submissions via Export / Import as long as the CSV has the SID column filled.
> 2 votes

# Answer
Is there a way? Yes.

There isn't any ready made solution though, you would have to read the data yourself and insert it into the database. Since webform has a dynamic use of the database, it would be tricky, since a user could change the webform and break imports.
> 0 votes

---
Tags: 6, webforms, importing-exporting
---


title: Including content types in a theme?

text:
# Question
Title: Including content types in a theme?
If I'm making a theme that I want multiple people to be able to download and install (not just making it for one client), what's the best way to include the content types? For instance, say it's a portfolio type of website, and has a content type called "project". I don't want anyone who downloads my theme to have to go in and create the content types by hand.

What are best practices in distributing a theme with requirements like that? Is there a simple module I could expect someone to install first?

# Answer
> 0 votes
If your theme code depends on certain content types being there, then that tells me that you are actually building a module plus a theme, and not just a standalone theme.

One way to do this is to use the Features module to export your content types and other settings. Then you probably want to move some of your theme functions into the module code, so that other themers can more easily build on top of what you've created.

---
Tags: theming, nodes
---


# Question
Title: Menu system - accepts extra args on path
Awhile back, working in Drupal 6, I found an issue in which a valid path, say:

> example.com/real/page

would be served if the following did not exist:

> example.com/real/page/fake-arg

I thought it was occurring only with pages defined through Panels and Views, and managed to implement a rather complex check (run during hook\_init()) for whether a panel should really be handling that path, and if not, call drupal\_not\_found().

**However**...

I just today realized that this same thing occurs with paths defined in Drupal core, e.g.

> user/7

gets served for

> user/7/blah

(This answer is what tipped me off: https://drupal.stackexchange.com/a/5080/834)

So evidently, this is happening by design (and through no fault of the CTools-related modules that instate pages through hook\_menu()).

I haven't fully been able to dig into menu\_get\_item() to figure out how it's accepting the extra args, but my question is: does anyone know a way to get around this behavior and make these non-existent paths result in 404s?

# Answer
> 3 votes
I don't think you can do that in a general way, this is a behavior that's by design and many modules rely on this, so you would break their optional arguments. In fact, relying on this is currently the only way to support optional arguments without defining a menu router item for every possible combination.

If you want to do it for a specific page callback under your control, you could check if there are any arguments passed to your function with func\_get\_args() and if so, return a 404.

Note that this "feature" might be removed in 8.x, I've seen it mentioned in an issue.

---
Tags: 7, routes
---


# Question
Title: Allowing authenticated users to create files through Service/Restful
I have setup a restful server running with the services module. I have also enabled to file resource. Using this setup I can successfully login from my client application, authenticate the session, upload a file using the file resource and then create a node with node resource. This all works fine and good as long as I am authenticated with an adminstrator but if I ever try and use a standard authenticated user I get this error back in response from the file resource:

```
Unauthorized: Access denied for user authuser

```

I looked all throughout the user permissions but I did not see any permission to allow authenticated users to create files. How would I do this?

# Answer
> 5 votes
Make sure "Save file information" is set for authenticated users

---
Tags: 7, nodes, users, services
---


# Question
Title: $form_id: What is the difference between #id and #value?
I am trying to find the $form\_id using the Devel module.

Sometimes when I output a form, $form\_id is output with a single value. However, sometimes the output of `dpm($form)` looks like this:

What is the difference between #value and #id here? Which is the $form\_id?

# Answer
> 2 votes
`$form_id` always has `_` in it. Because in hook\_form\_FORM\_ID\_alter() you always have to put replace FORM\_ID with $form\_id so you can't put `-` in function name.

```
$form_id: String representing the name of the form itself. Typically this is the name of the function that generated the form.

```

And `#id` is html safe id. id attribute for form tag.

---
Tags: forms
---


title: can't group the ckk fields

text:
# Question
Title: can't group the ckk fields
I am using drupal 6. I can create a group inside of a content type, but I can't see any way of attaching a field to the group. In a different installation of drupal on my computer, I see a box right under the new field name where you can enter a group, but this doesn't show up in this installation. Why would that be?

# Answer
You can drag a field under the group.

Fieldgroup is already included in CCK module.
> 0 votes

# Answer
You can achieve this functionality by using the Fieldgroup cck module.
> 0 votes

---
Tags: entities
---


# Question
Title: Call node information when rendering links
Alright, this one is a bit tricky. I'm using the theme() function and theme\_links\__system\_main\_menu to render the main menu in a specific way on the front page. All the menu items link too basic pages.

The idea is that when hovering over a menu item, a pop-up appears with the content of a field called 'Preview' that's on the basic page of which the menu item is linked to. The pop-up itself is a simple CSS thing, so what I'm looking for is a way to access the information of the node in question.

I know $variables contains the link to the node, is there perhaps a function that gives you node information by link?

# Answer
> 0 votes
Assuming that you need to access to $node to populate the preview:

You will need to load the node object for access to $node. So lets say you extract the href from $variables, you wont be able to load node based on the url, atleast I dont know any function that does it. You will need to extract (php explode etc) node nid and then use node\_load($nid) to load the $node object and then you can populate the preview based on a field of $node.

Where to write the code?

You can either override the theme function or use the preprocess, the preprocess for this should be (though not sure) yourtheme\_preprocess\_links\__system\_main\_menu(&$vars) and theme override will be yourtheme\_links\__system\_main\_menu. I hope you understand the difference between theme function override and preprocess. I'd suggest preprocess to add preview in $variables and then overriding theme function to use that value. OR, you can build the preview and add it as an attribute to the link.

Hope that helps.

---
Tags: 7, entities, routes, nodes
---


# Question
Title: (nginx) File field upload progress not working, but upload progress in FileField Sources works
Drupal 7.14, FileField Sources 1.4, Nginx, php cgi. File upload limit 1000MB. Using Chrome as browser

Everything has been configured fine.

I've tested using FileField Sources, upload about 700MB through Remote URL. Everything including the progress bar works without problem, even it takes too long time up be uploaded.

**But when upload from my computer;**

If upload small file, the upload progress is visible, but not showing any progress even the file uploaded as usual.

If upload large file, it will be same as above. But it will timeout (timeout after 30 seconds if using Chrome) (if using Opera, the timeout sometime after 17 seconds, sometime after 5 seconds).

The timeout error in Opera:

```
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /file/ajax/field_hcuba/und/0/form-j39oCcFwF3Y4J8hBu8A1HHms9oDs3xuhYIgLoZ0MQ2Q
StatusText: n/a
ResponseText: 413 Request Entity Too Large
nginx
ReadyState: undefined

```

The timeout error in Chrome:

```
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /file/ajax/field_hcuba/und/0/form-1smxhyxT7Xw1F6zjZul2gRxkMI7DNF8pkPRTUyW35SU
StatusText: n/a
ResponseText:
ReadyState: undefined

```

This only happen in Nginx server. In Apache, all works without problem.

# Answer
Nginx doesn't support upload progress in core, you will need to install - http://wiki.nginx.org/HttpUploadProgressModule

To show upload progress a webserver should implement - RFC1867
> 2 votes

---
Tags: 7, files
---


# Question
Title: Use Rules to create new content and fill the corresponding node_reference field
I want to use a button to create a new article.

I write two rules to do the following work

snapshot 2

snapshot 3

The **snapshot 2** creates a new content; the **snapshot 3** fills the field of the content just created.

I can't fill the node reference field; how can i do that?

The button I put is on a different kind of content type.

I hope some body can help me fix this article.

# Answer
I found how to fix my own problem

```
$node->field_YOURFIELD[LANGUAGE_NONE][0]['uid']=$userid;
$node->field_YOURFIELD[LANGUAGE_NONE][0]['nid']=$nid;

```
> 2 votes

# Answer
Perhaps you could have a PHP action like this:

```
$nid = arg(1); //Gets the nid from the url
$node = node_load($nid);
$node->field_YOURFIELD['und'][0]['target_id'] = 10; //nid of referenced node
node_save($node);

```

This works with the Entity References module. I don't know about the node reference module. It might be 'value' instead of 'target id'. You can use the Devel module to find out.

You'll need to enable the PHP module.
> 0 votes

---
Tags: rules, nodes
---


title: Securing only a part of a page

text:
# Question
Title: Securing only a part of a page
I am using login box on all pages. Is there a way to secure only the login box part of the page ?

# Answer
You can use SSL Certification for securing Login Box which opens the box on https. Add a Login link to your pages and it opens the login box on https.
> 0 votes

---
Tags: 6
---


# Question
Title: Contact form to notify the author of the node
i am building a real estate website where authorized users will be able to add some properties. I need in the property details page(node) to have a contact form with spesific fields and when that form submitted, the author of the node will be notified by email. Is that possible and how can i do this?

I am not a programmer so i would prefer a solution with existing modules.

# Answer
You may try the Privatemsg module.

> Privatemsg allows your site's visitors to send private messages to each other. Perfect for community oriented sites, such as forums and social networking sites. Many additional features are available as separate modules.
>
> ### Current features
>
> * send and receive private messages on a site (between multiple recipients)
> * threaded conversations (make it easier to keep track of messages and replies)
> * search private messages
> * tagging and filtering (helps organise conversations)
> * user blocking
> * e-mail notifications of new messages
> 1 votes

# Answer
The contact module - part of drupal itself makes it possible to allow users to be contacted from within their profile. A mail is sent to the user's email.
> 0 votes

---
Tags: 7, nodes, emails
---


title: How do I remove the commits in git?

text:
# Question
Title: How do I remove the commits in git?
I am using git to track my commits in a Drupal 7 site. I was involved in a project which uses git to move between production and development server. I made some changes in features and pushed it to the production server. I now notice the following error:

> The website encountered an unexpected error. Please try again later.

I am sure this is because of some feature errors, but at the same time I am not sure what feature caused this to happen.

I want to know is there a possible way to remove the commits by date. Like remove commits from 25th may? or Set header before 25th may?

# Answer
> 3 votes
To revert a very simple commit, this is enough:

git revert ba24a3fdeae4a3a034691308171d798d2ddbf93e

here that long string of characters is the ID of the commit you are reverting.

To get the ID of the commit see the git log.

---
Tags: version-control
---


# Question
Title: Views pager when view is running on Node Id
I have a view with a contextual filter of Nid running to display the current node. Does anyone know of a way to set up pagers within a view that can handle paging to next/prev nodes? So a 'next' link for the subsequent node and a 'prev' link to show previous node.

I would normally use custom pagers for this but this module does not work properly with views 3 that I have installed.

Any help or an alternative to custom pagers would be much appreciated.

# Answer
> 0 votes
I've used Previous/Next API for this kind of situation (it's only dev, but it worked for me, YMMV).

---
Tags: views, nodes, paging
---


title: Print out list of Imagecache presets

text:
# Question
Title: Print out list of Imagecache presets
I just need an array of the preset names, is there a simple way to do this?

# Answer
> 3 votes
imagecache\_presets

Get an array of all presets and their settings.

Parameters

reset: if set to TRUE it will clear the preset cache

Return value

array of presets `array( $preset_id => array('presetid' => integer, 'presetname' => string))`

---
Tags: 6, forms, media
---


# Question
Title: Why do Drupal.behaviours and document.ready behave differently?
I have the same piece of jQuery that works differently depending whether it is wrapped in document.ready or Drupal.behaviours. The code is intended to enumerate a list of tabs generated by the vertical tabs module.

Using

```
Drupal.behaviors.myModule = function (context) {
   $('ul.vertical-tabs-list li').each(function(i){
     console.log(i);
   })
}

```

Logs no output, but the following works as expected.

```
if (Drupal.jsEnabled) {
$(document).ready(function() {
      $('ul.vertical-tabs-list li').each(function(k){
      console.log(k);
      })
    })
 }

```

Why is there a difference and how can I get the first version to work?

# Answer
> 3 votes
Drupal.behaviours are similar to document.ready but Drupal make sures that on every ajax call code written in a Drupal.behaviour is executed again. While code written in document.ready is called once on page load.

---
Tags: 6, javascript
---


# Question
Title: Print array of imagefield fields for node type
I need to get an array of imagefields for a specific node type or even just all imagefields or all fields for a node type.

# Answer
> 1 votes
You can get a list of all fields for a particular content type using the `content_types()` function:

```
$type = content_types($type_name);

if (isset($type['fields'])) {
  $fields = $type['fields'];
}

```

From there you can just loop through and see what type of field each is, and act on it accordingly.

---
Tags: 6, media
---


# Question
Title: Change content in page.tpl.php depending on the page
I am creating a custom Drupal 7 theme and I have an image slider within page.tpl.php, I want to be able to change the images that it is cycling through depending on what page it is on.

I'm using the Views module with Views Slideshow.

If anyone can point me in the correct direction I will be very thankful.

Cheers,

Luke

# Answer
As you're already using a View to create your slideshow, could you not simply use an argument to change the View output based on URL? I would need to dig into the specifics of your site to help further, but that seems like the easiest thing to do - no custom functions necessary.
> 2 votes

# Answer
You could create a function in your theme template to determine what page you are on...

```
function YOURTHEME_section() {

    $section_path = explode('/', request_uri());
    $section_name = $section_path[1];
    $section_q = strpos($section_name, '?');

    if ($section_q) {
        $section_name = substr($section_name, 0, $section_q);
    }

    switch ($section_name) {
        case '':
            return 'section_home';
            break;
        case 'admin':
            return 'section_admin';
            break;
        default:
            return 'section_404';
    }
}

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: Changing image styles in a node view (Drupal 7)
In the node view of my custom content type I would like the image to stretch across the screen or at least be centered. As can be seen in the below screenshot currently the image does not get resized and is left justified. Would this be done through theming or some other means?

# Answer
> 1 votes
You can manage image-styles under

> admin/config/media/image-styles

and then use these styles to show up in your node view. Settings can be found on the "Manage Display" tab of your content-type. There's a little gear on the right side of the field row...

# Answer
> 0 votes
This is more of a styling question than a Drupal question, but you would probably want to do it in CSS with margin:auto.

# Answer
> 0 votes
I would solve this more with CSS than anything. If your body tag is already getting a class added to it based on the node type, you could do something like:

```
.page-nodetype img { width: 100%; }

```

The only thing that would make this hard is if Drupal is inserting the dimensions attributes into the HTML tag itself (e.g.: width="150"). That will override the CSS.

Or, just to center it:

```
.page-nodetype img { display: block; margin: 0 auto; }

```

---
Tags: 7, nodes, media
---


title: Show new navigation once user log in?

text:
# Question
Title: Show new navigation once user log in?
I'm building a site using Drupal 7 and have a question regarding navigation and roles. My site requires that a lot of content be accessible only to members. I'm wondering how I can show a secondary navigation element on the site once a user logs in? Obviously this would be tied to an authenticated user role.

Any assistance is greatly appreciated!

# Answer
> 1 votes
This module might do the trick:

http://drupal.org/project/menu\_item\_visibility

I've not installed it myself, but it seems to do what you're asking.

# Answer
> 1 votes
I think it's worth mentioning that in Drupal, if you don't have access to view a node, then you won't see the link to that node if it's in a menu.

So I think you first need to find a node access control module. Something like Content Access which is based on ACL module.

Then you need to add those nodes as a menu item into your menu. If people don't have access to any of the nodes on that menu, then that menu will not show anything.

---
Tags: users, navigation
---


title: Are hooks indexed when Drupal loads?

text:
# Question
Title: Are hooks indexed when Drupal loads?
Wondering how Drupal manages hooks outside of the core in modules. Seems like parsing the code in modules would add a lot of overhead, and that it's more likely that the code is doing something else to manage the calls; for example, indexing or compiling the code when Drupal boots for the first time.

If there's a difference between how 6 and 7 handles this, please explain how each handles it, or clearly state which version you've explained.

# Answer
I can't speak for Drupal 6 (haven't used it in a while), but in Drupal 7 the standard method used to invoke a hook is something like the following:

```
$modules = module_implements('some_hook');
foreach ($modules as $module) {
  // Call the hook
}

```

`module_implements()` caches the hook implementations, and as such the index is only rebuilt when the caches are cleared (or more specifically, the bootstrap cache).

As for parsing the code in modules, this falls outside of Drupal's jurisdiction; PHP will parse *all* of the code in *any* included file. Since hooks must reside in a .module file (or at least a file that's explicitly included from a module file), and all enabled module files are included on each page request, the whole file will be parsed every time.
> 5 votes

---
Tags: hooks
---


# Question
Title: Views 3 + field collection: relate only the first referenced field collection item
I'm using Views 3 and Field collection 7.x-1.0-beta3. As a simplified example, say I've a field collection called Image - which itself has two fields, an image file and a text caption. My content type, Page, includes a multi-value field to reference one or more Image(s).

In my view, I want to list several Page nodes, and display the image file field taken from only the *first* of each node's referenced Image field collection entities.

**This works, but...**

I have one solution that does work but feels clunky and indirect: Add the Image collection-reference field, and use the multiple-value settings to restrict to the first value (a la this post). However, then I have to have a view mode for the Image field collection that prints only the image file field, in the desired image style.

**What would be awesome:**

I've tried a different route using the Relationships settings. I can add a relationship from node to its Image field collection. Then, I can add the image file field, pulling from the relationship. BUT, that creates a new result for each of the Image field collections being referenced... and I can't find an option to key the relationship off the first value only (similar to displaying only the first value when I'm just going through adding the field, in my "this works" solution above).

I realize this may be impossible - if Views can't create the necessary query? Just wondering if I have missed something though I've gone through the settings several times.

**Edit: Drupal 6 / Views 2 does it!**

Okay, I'm not crazy - see screenshot. I think that's exactly what I'm looking for here.

# Answer
If you create a view with the field collection relationship this is possible. Besides the field with the image you need to add another field with the image delta. When you add this field exclude this from display.

In the views filter add a filter on this delta field and set this filter to equals 0.

Now you've got a view with just one (the first) image per node!
> 2 votes

# Answer
Hmmm. Apparently the Delta option (that I referred to in the D6 / Views 2 screenshot) is back again in the relationship configuration options - in Views version 3.3. Maybe it was just temporarily gone in a prior 3.x version...?

Setting this Delta to 1 would achieve the result I wanted.
> 0 votes

---
Tags: 7, views
---