title: Extract the database abstraction layer

text:
# Question
Title: Extract the database abstraction layer
If it's possible, how can I go about extracting the database abstraction layer to use in a non-Drupal site?

# Answer
Are you looking to use the Drupal database API exactly as it currently exists, or do you just like the idea of a PDO abstraction layer?

If you're really trying to break out of Drupal's bootstrap and code, then check out using PHP Data Objects (PDO):

Now, if you just want to use Drupal's database API to work with a database outside of Drupal's database (but within a custom module or within a custom .php file that bootstraps the database), you can really easily do so by switching databases via `db_set_active()`. You'd throw something like this in your settings.php file:

```
<?php
$databases = array();
$databases['default']['default'] = array(
  // Drupal's credentials here...
);
$databases['my_other_db']['default'] = array(
  // My other database credentials here...
);
?>

```

and then you'd activate it via:

```
<?php
db_set_active('my_other_db'); // Use my_other_db
// do stuff using Drupal 7's awesome database API
db_set_active(); // Go back to Drupal's db.
?>

```

I wrote a blog post that sums up how to bootstrap Drupal in a standalone PHP script to use certain layers, you may find this useful: -
> 1 votes

# Answer
If you want to use the Drupal database code in a website, without bootstrapping Drupal, you need the following files:

* includes/database/database.inc
* includes/database/sqlite/database.inc
* includes/database/mysql/database.inc
* includes/database/pgsql/database.inc

The code in those files needs to be changed, as:

* The code uses the DRUPAL\_ROOT constant. You could remove the code using that constant, and replace it with code that automatically loads the include file containing the class. For example, the following code uses `DRUPAL_ROOT` because Drupal cannot use its code registry until there isn't a database connection active, as its code registry uses a database table.

```
// We cannot rely on the registry yet, because the registry requires an
// open database connection.
$driver_class = 'DatabaseConnection_' . $driver;
require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
$new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
$new_connection->setTarget($target);
$new_connection->setKey($key);

```

It could be rewritten as follows, if you register your own function with spl\_autoload\_register().

```
$driver_class = 'DatabaseConnection_' . $driver;
$new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
$new_connection->setTarget($target);
$new_connection->setKey($key);

```
* The functions use the global `$databases`, which is normally defined in the settings.php file. You could replace that variable with a static property of the Database class.
> 3 votes

---
Tags: 7, database
---


# Question
Title: Running triggered rules actions in the background?
I am using triggered rules to set off potentially lengthy actions on nodes, e.g. automatic node translation using Google Translate. Running those actions during the node creation page request slows down the response and potentially uses up server resources.

Instead, I'd like to enqueue the actions, so that they may be executed during the next cron run, or via the Queue API. Is there a known way to achieve this? Is it possible to do that using Rules Scheduler?

# Answer
Turns out you can use Rules Scheduler for this. Here's the recipe:

* Create an action set with the actions to run in the background
* Add the action "Schedule component evaluation" to your trigger, choosing the action set you created above
* Set the "Scheduled evaluation date" to `now`

When your trigger fires, its actions will be called at the next cron run. That was simple!
> 1 votes

---
Tags: 7, rules, queue
---


title: New taxonomy template

text:
# Question
Title: New taxonomy template
On Drupal 7, I am trying to create a different version of the default taxonomy template file for a theme. When a user clicks on a taxonomy term, the new template file is used instead of the default one.

So far all I have managed to do is finding the correct template file name (page--taxonomy.tpl.php). The problem that I have is that the variables copied from the template file the Taxonomy module uses simply don't work, as they are obviously not being populated.

```
<?php if ($content = render($page['content'])): ?>
  <div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes.' channels-'.strtolower(str_replace(' ','',$term_name)); ?>">
    <?php if (!$page): ?>
      <h2><a href="<?php print $term_url; ?>"><?php print $term_name; ?></a></h2>
    <?php endif; ?>
    <div class="content">
      <?php print render($content); ?>
    </div>
  </div>
<?php endif; ?>

```

So any variable beginning with $term is NULL. What/where do I call to populate these?

# Answer
The only template file used from the Taxonomy module is the taxonomy-term.tpl.php file. If a theme implement that template file, it receive the following variables. (The list is partial; for the complete list see the documentation.)

* `$term_url`: Direct URL of the current term
* `$term_name`: Name of the current term
* `$term`: Full term object

page--taxonomy.tpl.php is a page template that Drupal uses for pages with a URL matching taxonomy/\*. It is a page template, for which the variables are different. In particular, it doesn't get any `$term*` variable.

### References
> 1 votes

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


# Question
Title: How to create multiple user account types in drupal 7
I want to customize the default registration process in drupal 7 like Paypal.

Users can choose their account types to register and each account type has some corresponding fields to fill information.

For example in Paypal have 3 account types : Personal, Premier, Business

In drupal I only see 2 account types(anonymous and authentication), how can I add more ?

# Answer
> 2 votes
*Anonymous user*, and *authenticated user* are two default roles used by Drupal (what other CMS's would call account types).

You can add custom roles from admin/people/permissions/roles.

Once you created the new role, you can change the permissions given to that role using the "edit permissions" link that appears to the right side.

If you then need to add new fields for user accounts having a specific role, you can use the Field Permissions module.
Drupal allows you to add new fields to the user accounts, from admin/config/people/accounts/fields, but the fields are visible for every user account, independently from the roles those accounts have.

The Field Permissions module allows you to set who can enter a value for a field, who can edit a value for a field, and who can view the value of that field.
For example, if you want a "Editor ID" field that needs to be filled only from users with the editor role, you can add the permission of creating a value for that field, and editing it to users with the editor role; other users should be allowed to see that field, as well as the users with the editor role.

---
Tags: 7, users
---


# Question
Title: how to extend ctools functions in my own js file?
I am trying to extend the ctools model functions in my JavaScript file but not getting the exact way.

In ctool model.js contains `modalContentClose = function(){close(); return false;};` which I want to override in my JavaScript file to add more functionality.

I have tried to use the following code, but it doesn't work.

```
function extends modalContentClose() {
  // Some alert here.
}

```

# Answer
> 4 votes
JavaScript doesn't allow extending a function with another one. If you want to extend `modalContentClose()` you just redefine it in your JavaScript file that is included after the JavaScript used by ctools.module.

```
modalContentClose = function() {
  // Add your own code.
  close();
  return false;
};

```

Your version of `modalContentClose()` cannot refer the previous `modalContentClose()`, if you don't save it in a new variable, as with the following code.

```
originalContentClose = modalContentClose;

modalContentClose = function() {
  // Add your own code.
  originalContentClose();
};

```

---
Tags: javascript, chaos-tool-suite
---


# Question
Title: Optimal Settings.php for Pressflow + Varnish + memcache
I am using pressflow having varnish + boost + memcache and also using cloudflare caching, I have seen some variable forms of settings.php file on forums and I am confused whether mine is optimal for best usage of all these caching mechanism :

```
# Varnish reverse proxy on localhost
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');

# Memcached configuration
$conf['cache_inc'] = './sites/all/modules/memcache/memcache.inc';
$conf['memcache_servers'] = array(
         '127.0.0.1:11211' => 'default',
         );
### END Mercury settings written on 2011-11-01T07:12:49-04:00

```

# Answer
Unless you are doing something quite unique, using boost & varnish is usually overkill. If you have varnish setup exactly how you want it, I would just use varnish.

Here is an example settings.php. It is a multisite safe memcache configuration thanks to the memcache\_key\_prefix setting.

```
<?php
// Skip db query that checks for blocked IP's.
$conf['blocked_ips'] = array();

// Reverse proxy settings.
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array(
  '127.0.0.1',    // Localhost
);

// Use memcache for caches, locks, and sessions.
$conf['cache_inc'] = './sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = './sites/all/modules/memcache/memcache-lock.inc';
$conf['session_inc'] = './sites/all/modules/memcache/memcache-session.inc';

// Memcache Settings.
// Set memcache server.
$conf['memcache_servers'] = array(
  '127.0.0.1:11211' => 'default',
);
// Set memcache bins.
$conf['memcache_bins'] = array(
  'cache' => 'default',
  'cache_form' => 'database',
);
// Set memcache prefix to be the location of the settings.php file.
$conf['memcache_key_prefix'] = basename(realpath(conf_path()));
// Try to use a persistent connection.
$conf['memcache_persistent'] = TRUE;
?>

```
> 3 votes

# Answer
Earlier it was believed that Boost+Varnish do work good if configured correctly - Is it redundant to use the "boost" module if varnish is used?, has this changed by recent developments.
> 0 votes

---
Tags: proxies, caching
---


# Question
Title: "Rate Module" How to put the number inside the button?
http://drupal.org/project/rate

As you can see, the "yes/no" widget on the bottom of the screenshot is:

\[button\] \[number\]

The number is not part of the button. How to make it like this instead:

\[button number\]

edit: a perfect example, the thumbs-up/thumbs-down rating widget on Yahoo Answers: http://answers.yahoo.com/question/index;\_ylt=Ao37OQz9iO3ZJvacOl9pH8\_j1KIX;\_ylv=3?qid=20121104010935AAs5NQk

The number is in the button. Clicking anywhere on that button registers a vote.

# Answer
> 0 votes
This is done by using some CSS.

look at the HTML structure there. 'LI' tag is used there. Just use the anchor style to LI tag.

background: #EEE; border: 1px solid #CCC; margin-right: 3px;

Use this style to li and remove anchor border. Also change the hover style of anchor tag.

Use firebug to find the structure.

---
Tags: 7
---


# Question
Title: How to change Views field settings programmatically?
**I would like to change some field settings in a given view** created with Views **programmatically**.

For example, I would like to change the "***Formatter***" and "***Image style***" settings of an *Image field*. This is what the settings of this field look like when I export this view:

```
/* Field: Taxonomy term: Natural images */
$handler->display->display_options['fields']['field_gallery_natural_images']['id'] = 'field_gallery_natural_images';
$handler->display->display_options['fields']['field_gallery_natural_images']['table'] = 'field_data_field_gallery_natural_images';
$handler->display->display_options['fields']['field_gallery_natural_images']['field'] = 'field_gallery_natural_images';
$handler->display->display_options['fields']['field_gallery_natural_images']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_gallery_natural_images']['type'] = 'colorbox';
$handler->display->display_options['fields']['field_gallery_natural_images']['settings'] = array(
  'colorbox_node_style' => '',
  'colorbox_image_style' => '',
  'colorbox_gallery' => 'post',
  'colorbox_gallery_custom' => '',
  'colorbox_caption' => 'auto',
  'colorbox_caption_custom' => '',
  'display_empty' => '',
  'custom_text' => '',
  'empty_callback' => 'mymodule_empty_fields_no_data',
);

```

I would like to change the "Image style" of the Colorbox formatter somehow like this:

```
$handler->display->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';

```

and save that. How should I do that?

Like here:

---

# EDIT 1.

Maybe I should use `views_save_view()`:
http://api.drupal.org/api/views/views.module/function/views\_save\_view/7

It saves a view - so maybe I should query the whole view, change that, and use this function. But how exactly?

# EDIT 2.

I found in `views/includes/admin.inc` that the given view gets saved like this: `$form_state['view']->save();` in `views_ui_edit_view_form_submit()`.

I already know how to change "Image style" of an Image field in a given view mode programmatically (as on "Manage display" tab after clicking the gear), but now I would be happy if I could do something similar with a given view.

# Answer
**UPDATED**:

You can use this code snippet to change a view without `views_alter`:

```
$view = views_get_view($view_name, TRUE);
$view->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';
views_save_view($view);

```

Change `default` display ID if you want to use display other than the default.

---

If you have exported the view to code using `hook_views_default_views()` or the Features module, there is a hook to alter the views programmatically:

```
/**
 * Alter default views defined by other modules.
 *
 * This hook is called right before all default views are cached to the
 * database. It takes a keyed array of views by reference.
 *
 * Example usage to add a field to a view:
 * @code
 *   $handler =& $view->display['DISPLAY_ID']->handler;
 *   // Add the user name field to the view.
 *   $handler->display->display_options['fields']['name']['id'] = 'name';
 *   $handler->display->display_options['fields']['name']['table'] = 'users';
 *   $handler->display->display_options['fields']['name']['field'] = 'name';
 *   $handler->display->display_options['fields']['name']['label'] = 'Author';
 *   $handler->display->display_options['fields']['name']['link_to_user'] = 1;
 * @endcode
 */
function hook_views_default_views_alter(&$views) {
  if (isset($views['taxonomy_term'])) {
    $views['taxonomy_term']->display['default']->display_options['title'] = 'Categories';
  }
}

```

For example:

```
/**
 * Implements hook_views_default_views_alter()
 */
function MYMODULE_views_default_views_alter(&$views) {
  if (isset($views['VIEW_NAME'])) {
    $views['VIEW_NAME']->display['default']->display_options['fields']['field_gallery_natural_images']['settings']['colorbox_node_style'] = 'thumbnail';
  }
}

```

Remember to clear the cache and do revert of the view to apply changes.
> 18 votes

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


title: Individually place menu items

text:
# Question
Title: Individually place menu items
How can I position each menu item individually in Drupal 7? I've created a quick visualisation how I want it to look like:

The problem is that I still want to have hover effects and highlight the page I'm currently on. The menu don't need to be dynamic because the menu items won't change.

Any Ideas?

# Answer
> 0 votes
Try `theme_links`

Like

```
<?php
print theme('links', array('links' => menu_navigation_links('menu-site-menu'),
'attributes' => array('class'=> array('links', 'site-menu')) ));
?>

```

---
Tags: theming, routes
---


# Question
Title: How can I hide the Organic Groups Audience selection?
I don't want the OG audience selection to appear on a custom content type I have created for groups. I'm only providing the link to create the custom content within a group so the group they are in is pre-selected and it makes no sense to display it. I can't believe there is not a OG option to turn this off so how can I accomplish this?

# Answer
You can set #access to FALSE to hide elements like this:

```
/**
* Implements hook_form_alter()
**/

function yourModule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'yourFormId':
      // We should remove the group check box from users, Its always going to be
      // checked for project content type.
      $form['group_group']['#access'] = FALSE;
      $form['group_access']['#access'] = FALSE;
      break;
    }
}

```

Above I removed the check box that says "group" and group audience.
> 2 votes

# Answer
Look at the FAPI docs and hook\_form\_alter on your content type. For the appropriate widget try setting the widgets `#access` key to FALSE. If it's not horribly coupled to OG's interworkings that should work (and assuming its default value is ok). I would recommend doing this for everyone who is not the uid of admin.
> 0 votes

---
Tags: 7, organic-groups
---


# Question
Title: menu_tree_page_data() is not loading sub-menu items
I have created a menu that has a handful of top level items and some sub-menu items. it is similar in structure to my "main menu". It is my understanding that each top level menu item is an array, which also contains an array of menu items that are "below" that menu item.

When I print out the array of the menu it will not show the sub-menu items. Am I doing something wrong?

```
$mm = menu_tree_page_data('menu-second-menu');
print_r($mm);

```

My ultimate goal is creating X amount of individual menus, and display them in various places throughout the theme.

When I print the array values for the "Main Menu", which is assigned to a block and working, I do see the sub-menu items right where I'd expect them to be.

# Answer
If you want the whole array of the menu use this function,

```
menu_tree_all_data('MENU_NAME');

```

If you find any difficulty, please let me know!
> 2 votes

# Answer
But isn't menu\_tree\_page\_data() suppose to do the task as well? If it doesn't we need to know why so we can address the issue right to the cause of the problem. I am using i18n\_menu\_translated\_tree() and apparently it is also using menu\_tree\_page\_data() to call the menu. But due to this factor, my translated menu is not showing properly (i.e. submenu not shown).

Anyone who has knowledge on this issue kindly share. Thanks in advance.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Panels- How can I show the related terms pane only if the term being displayed has only the root as parent?
I am using the awesome Panels module to override the default taxonomy display. I am using the Related Terms content pane (built-in to Panels) to show children of the current term.

My vocabulary looks like this:

1. Country
2. State
3. City

What I would like to do is show the child terms (related terms pane) only for countries, not states or cities. In other words, I would like to show the related terms pane if and only if the term has no parents except the root parent.

However, the only *Visibility Rule* that seems to apply is **Term has Parent(s)**, which requires a user-created term (not the root term) to be selected. I could select all of the terms and then check *Reverse*, but I have hundreds of locations and more are being added all the time, making this unfeasible. Is there some other way?

# Answer
> 2 votes
I wrote something quick together over in Different variant for other Taxonomy hierarchy within vocabulary, that gives a selection rule for the term level.

It sounds like that would help you.

---
Tags: taxonomy-terms, panels
---


# Question
Title: How can I listen for drupalOverlayBeforeClose in custom jQuery?
I am monitoring a particular form for changes and want to warn the user before they attempt to navigate away from the form without submitting it. I've successfully gotten this working in all instances except for the overlay close button – because that element is bound to the `Drupal.overlay.close()` function, a user is able to click it and immediately close the overlay, even though I'm listening for all `$('a')` clicks.

I looked inside of `modules/overlay/overlay-parent.js` and see that it provides the `drupalOverlayBeforeClose` event so that other scripts can respond and stop the overlay from closing if needed, but I can't figure out how to implement this. Do I just listen for this event globally, through the `$(document)` or something? Or do I need to extend the Drupal object and attach my function to this event somehow?

# Answer
> 4 votes
You need to use the following code,

```
jQuery(document).bind('drupalOverlayBeforeClose', function(event) {
   // your code
   return false // This will prevent the overlay from closing.
});

```

click, dbclick and other methods are shortcut methods for `bind('click', function(){})`, `bind('dbclick', function(){})` respectively. However there is no shortcut method called **drupalOverlayBeforeClose**, that's why the following code didn't worked,

```
$(document).drupalOverlayBeforeClose(function(event) {

});

```

So you need to bind **drupalOverlayBeforeClose** explicitly using bind. If you return false in your callback, then the overlay won't be closed.

Hope this clarifies the answer.

# Answer
> 3 votes
Try following code

```
jQuery("#overlay-container").find("iframe").contents().find("#overlay-close").click(function (event) {
    console.log('Clicked on close overlay link');

    event.preventDefault();
    event.stopPropagation();

    var r = confirm("Do you want to close overlay?");
    if (r == true) {
        Drupal.overlay.close();
    } else {
        //do something else
    }

});

```

When user will click on close overlay link, a confirming dialog should display.

---
Tags: 7, javascript, modal-dialogs
---


title: how to inject JQuery into a D7 page

text:
# Question
Title: how to inject JQuery into a D7 page
I have a Drupal 7 view page where I want to change the behaviour of the submit button by using the jQuery code below. How do I do this in Drupal 7?

```
$('#reset-button').click(function() {
  $('#views-exposed-form').each(function() {
    this.reset();
  });
  $('#submit-button').click();

  return false;
});

```

# Answer
> 4 votes
You can add your code in a JS file say somescript.js and save it in your theme folder. In the theme.info file add the following line

```
scripts[] = somescript.js

```

This will add `somescript.js` to all pages by default. If you want it for a particular page add a conditional check and use `drupal_add_js(PATH_TO_JS)`
For more info check out Managing JavaScript in Drupal 7

# Answer
> 2 votes
To use `$` you have to introduce

```
jQuery(function($) {});

```

at the begining.

```
jQuery(function($) {
    $(document).ready(function(){
      $('#reset-button').click(function() {
       $('#views-exposed-form').each(function() {
         this.reset();
        });
       $('#submit-button').click();

       return false;
      });
     });
 });

```

To add this js file to a page you have to use

```
 drupal_add_js(drupal_get_path('module', 'module_name').'/path/to/js');

```

# Answer
> 0 votes
If you do not want to write a whole new module to inject custom JavaScript code, then try this module http://drupal.org/project/js\_injector.

I have been using this module from long time and it works beautifully.

# Answer
> -1 votes
Good idea! Regarding this I found painless solution. I installed jQuerify from here https://chrome.google.com/webstore/detail/jquerify/gbmifchmngifmadobkcpijhhldeeelkc It injects jQuery 1.8 even in HTTPS pages with one click with no conflict to Prototype )))

---
Tags: 7, javascript
---


# Question
Title: Extending Drupal Functionality to Custom PHP Page
I have Drupal 7 site which is working fine. I added a custom PHP page to my site in the root directory of it. I want to extend the Drupal application functionality to that one page so that I can have access to the different Drupal classes and basically extend Drupal through my page. What includes do I need at the top of my page to be able to access the Drupal application as if I were within the Drupal site?

# Answer
> 6 votes
The only file you need to include is '/includes/bootstrap.inc', but you also need to define the `DRUPAL_ROOT` constant and run `drupal_bootstrap()` to have access to the API/database/etc.:

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Your code here

```

It's exactly the same code that you'll find in the standard index.php file, minus a call to `menu_execute_active_handler()` which isn't necessary if you dont want to build and output a normal Drupal page.

# Answer
> 6 votes
Even though Clive's answer answers your question correctly, I'd still like to present the point of view that while what you're doing is not *wrong* per se, it's not a very good pattern as all custom code in Drupal is designed to reside under sites/all.

The correct way to go about this is to have a custom module, that implements the horribly misleadingly named hook\_menu -hook.

I'll omit the details of creating and enabling a custom module as there's plenty of references out there for that, but this is what you need to do in your module that I'll call *custommodule* :

```
function custommodule_menu(){
  return array(
    'path_you_want' => array(
      'page callback' => 'custommodule_callback',
      'access callback' => TRUE
    )
  );
}

function custommodule_callback(){
  // do whatever you want to do and return what you want rendered on the page content area.
  return "Hello world from my custom callback";
}

```

This is pretty much the bare minimun example and just hook\_menu has enough options to tweak access, url parameter passing, cache handling etc to take care of most any scenario necessary.

Yes, this is a couple of steps more work than what you were doing, but is far cleaner, more future proof and keeps all code where it's supposed to be. It's also quite a bit better aligned with how Drupal expects custom stuff to interact with it, so your page won't break if Drupal changes the way it bootstraps for some reason.

---
Tags: 7
---


# Question
Title: How can I configure drupal to share modules between two installations on the same server?
Say I want to run `siteA.com` and `siteB.com` from the same remote server. How can I share the modules but not site specific configuration. I don't want them to have the same titles use the same modules but it seems a waste of space to be installing the same modules if they are running on the same server.

Please note: I selected the answer below because it looked like an answer. However, seems to be useful only if the server is local? I do not use the terminal to connect to my site. I wouldn't be sure how to go about that either other than trying to do it via some shh connection.

# Answer
> 1 votes
There is a great way of accomplishing this, it's called multi-site. See http://drupal.org/documentation/install/multi-site and http://drupal.org/node/43816 for a start.

A great project that offers multi-site hosting is Aegir. In Aegir you can even create multiple platforms that run 1 or more sites. See http://aegirproject.org

1 thing: you can not run multiple sites from a subdirectory if you run with Aegir/Drupal, that won't work with how Drupal is designed, but if your running on some GNU/Linux, then you might be able to symlink something together.

It's true you can use the sites/all/\* folders to share modules/themes/libraries, but 1 thing is missing: In the sites/ folder, you have to create a directory, containing the config files, files directory (etc) for every individual site that you want to run.

You could also offer multiple sites from 1 directory via an alias, but that's not what your looking for now i believe, just as an extra bonus tip. ;) Hope this helps a bit.

# Answer
> 0 votes
You can use sites/all folder to share modules between any number of sites.

> This directory should be used to place downloaded and custom modules and themes which are common to all sites. This will allow you to more easily update Drupal core files. These modules and themes should be placed in subdirectories called modules and themes as follows:
>
> sites/all/modules
> sites/all/themes

---
Tags: multi-sites
---


# Question
Title: How to create a custom Aegir Drupal interface
I'm interested in using Aegir to deploy Drupal websites. I'm wondering if there is a way to customize the user experience of setting up a new site, while still maintaining the Aegir mechanism. Probably something more like the standard Drupal setup screen.

# Answer
> 1 votes
Yup, create a theme with all things you want, some custom modules to do more heavy lifting and there you have it and install both on your Aegir server. (working on similar idea i have for Aegir, including fcgi support, so i can jail sites to a user, sell them in a store and let the users fix their own sites.)

And / or you could use something like http://drupal.org/project/hosting\_services to write something yourself. (and loads more)

---
Tags: aegir
---


# Question
Title: Adding extra fields to Site Contact Form
This seems strangely difficult to me. What I thought would just be a case of adding extra fields a bit like adding fields to Content Types. But no. I can't locate any facility to add say a phone number field to the Contact form? Anyone out there know?

# Answer
> 20 votes
Expecting forms fields to be configured like content types is an over-generalization. Content types are for **content** (text, image, etc.) of the website, and more specifically, in Drupal, for nodes (the main piece of content in Drupal). Using the Field and Field UI module, one can easily adds fields to content type using a Web UI. Except for some specific cases, a form is not part of the content of a website but rather a way for users to add and edit information, sometimes content and sometimes not.

To customize (i.e. alter) a form in Drupal, the usual way is to create a custom module that implements the `hook_form_FORM_ID_alter` hook. This way, you can add form elements to existing forms provided by other modules. To use the information for fields added to the contact form this way, you will also need to alter the sent mail using an implementation of hook\_mail\_alter(). The following guide walks you through both steps in Drupal 7. (Note also this comment)

A non-code solution is to use the Webform module that provides a *form* content type and let you add forms as content to your website. These forms are configurable through a Web UI. Various processing steps can be configured for the information submitted through these forms. One of them is email sending. Using it for a custom contact form is a common use case. Webform comes with its own concepts and extension points. While it may prove to be a easier and faster solution for a one time simple forms, it may also reveal to be over-sized and complex to customize once a certain features threshold has been reached. The cost to add extra-features to a webform can then outperform the gain of avoiding writing a custom module in the first place.

# Answer
> 1 votes
It depends on what module you are using for your contact form. Some modules will provide a backend interface that requires no programming to add additional fields. A very popular module with this functionality is Webform.

Barring that, forms in Drupal can be altered by writing a custom module using the hook\_form\_alter hook. There are lots of tutorials out there on mdoule development and using this particular hook.

# Answer
> 1 votes
If your using core Contact module, hope the Contact form fields module might get finished soon for Drupal 7.

> This module allows to add additional fields to site wide contact form like the profile module interface. Admin can define the fields and those will be available on site wide contact form. Please note that these fields will not be available to personal contact form for now as I don't see any specific needs.

If you want something now: 4 options:

* Use a node type and transform it into a contact form.
* Use a webform.
* Build a custom module
* Or even better: fork/help the contact\_field module! The project page has just been updated, so it's at least moving again and would, ones finished, offer a very nice way of adding fields, just like on content types.

(adding this for search bot arena ;) )

# Answer
> 0 votes
Here is a sample code which shows how to add custom fields to the sitewide contact form via the forms api: new form fields example.

Enjoy!

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


# Question
Title: notice after entering a function in template.php
I get the following notices on every page:

```
Notice: Undefined index: node in myZen_preprocess_page() (line 242 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).
Notice: Trying to get property of non-object in myZen_preprocess_page() (line 242 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).
Notice: Undefined index: node in myZen_preprocess_page() (line 246 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).
Notice: Trying to get property of non-object in myZen_preprocess_page() (line 246 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).

```

I put the function I need to use the files page--content-type, and is as follows:

```
function myZen_preprocess_page(&$vars) {
   if ($vars['node']->type == 'mappe'){
     $vars['theme_hook_suggestions'][] = 'page__mappe';

    }
  else if ($vars['node']->type == 'fatti_e_risorse'){
    $vars['theme_hook_suggestions'][] = 'page__fatti_e_risorse';

  }

  }

```

Can I disable notices or fix this? thank you!

# Answer
> 3 votes
That notification is displayed because the `node` key of the `$vars` array is not always defined in `hook_preprocess_page()` function.

Use the following code, which first checks if the `node` key exists and then continues. It also uses the `switch` statement, which is easier to read if you only need to check the node type and use one condition:

```
function myZen_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    switch ($vars['node']->type) {
      case 'mappe':
        $vars['theme_hook_suggestions'][] = 'page__mappe';
        break;

      case 'fatti_e_risorse':
        $vars['theme_hook_suggestions'][] = 'page__fatti_e_risorse';
        break;
    }
  }
}

```

---
Tags: theming, hooks
---


# Question
Title: What database table can be emptied in order to make database lighter?
Are log files in drupal take a lot of space? I want to create a dump file but it's over 1000mb. What tables can be harmlessly emptied from the database directly or through drupal interface?

# Answer
> 2 votes
Usually all tables with `cache_` prefix are safe to be emptied.

The log table records can take a lot of space, depending on your settings on how many log messages you want to save. You can configure this at `admin/config/development/logging`.

How many nodes/users do you have on the website? Do you have enabled the core search module? What other modules do you have?

If your website has tens of thousands of nodes and users, 1GB is a normal size of the database dump.

---
Tags: performance
---


title: How to create a module with forms?

text:
# Question
Title: How to create a module with forms?
I am little stuck with creating a module for drupal.

I would like to show users a link: "Create", then to take them to a page where will be forms.

Can someone post little piece of code so i could see how to implement other...

Thank you!!!

# Answer
> 2 votes
One of the best way to learn how to do develop various common tasks is with Examples module.

Check especially the `form_example` module which has all necessary instructions and code examples.

# Answer
> 0 votes
i have made a form via module u may have a look

Custom module error, does'nt show on the page

For any queries feel free to ask. Thanks

---
Tags: 7
---


title: Need real help on this module

text:
# Question
Title: Need real help on this module
I'm really need a good documentation or some kind of HowTo for Google Font module,i installed it and i choosed my Google font and what after? i m asking if i need to do some manual css or php work or just some other configuration in the GUI .
Thank you very much

# Answer
> 3 votes
As the module page desription says development of this module has been stopped in favour of @font-your-face

@font-your-face is widely used now and has decent documentation, so you should use this one instead of Google font.

Module page description,

> IMPORTANT: I've decided to combine forces with @sreynen, the maintainer of the magnificent @font-your-face module. That modules does not only support Google Fonts, but also several other font providers and combines all those fonts in a very user-friendly interface. I will not improve the Google Fonts API module anymore. So please switch your site to (the 7.x-2.x version of) @font-your-face in favor of Google Fonts. Thanks ;)

---
Tags: theming
---


# Question
Title: How to get nid of all nodes that are displayed inside a view?
I have view named 'xyz' set on example.com/xyz. I want to access nid of nodes that are shown by 'xyz' and show them on example.com/abc. I want to do it in a custom module. What hook i can use?

I tried to look into views API but no ups there.

# Answer
> 0 votes
You can use `views_get_view_result($name, $display_id = NULL)`

*API Docs:* `views_get_views_result();`

# Answer
> 0 votes
```
Get the result for the current view:
<?php
  function views_get_current_view_result() {
    $view = views_get_current_view();
    return $view->result;
  }
?>

```

Heed that only the view items for the first page are returned. If the result array should contain all items then set the numbers of items per page to 0 (no limit).

**Structure of the result array**

The Array contains an object for each view item. Imagine a site has only one node then a node view type without fields and sort criteria would look like this:

```
<?php
Array
(
    [0] => stdClass Object
        (
            [nid] => 1
        )
)
?>

```

Refer this for more detail

---
Tags: views
---


# Question
Title: Which module for responsive images without Apache?
> **Possible Duplicate:**
> Handling Mobile Images in Responsive Drupal 7 Theme

I'm searching a good module to manage responsive images.

My site is build with Omega theme and the site will be published on a server that doesn't use Apache, so I can use modules that use .htaccess.

Which module do you suggest for my case?

# Answer
> 1 votes
try to use these modules. also suggest to use Adaptive theme.

http://drupal.org/project/responsive\_images
http://drupal.org/project/resp\_img

---
Tags: 7, media, theming
---


# Question
Title: How to upload file in Webform content type
I want to be able to upload a file with Webform, is their any way to do this?

# Answer
Yes you can upload files to webform. Create field for resume by choosing type as file. Check following screenshot
> 3 votes

---
Tags: 7, webforms, files
---


# Question
Title: Taxonomy search block - Search for e.g. "mac" -> Go to URL /tags/mac
I just want a simple "search" block for the tags taxonomy. It should work like I wrote in the title:

If you search for the tag "**x**", it should automatically go to the URL /tags/**x**.

I'm aware that it may result in "Page not found", but that's ok.

It's more like a "go to URL" block rather than a search.

# Answer
> 1 votes
You can use Custom Search module. This module allows you to manipulate search functionality.

It has sub module called **custom search Taxonomy** which allows you to search according to taxonomy terms.

This allows you to configure path also.

If you want to use custom search paths, enter them here in the form path|label, one per line (if only one path is specified, the selector will be hidden).

The \[key\] token will be replaced by what is entered in the search box, and the \[terms\] token will be replaced by the selected taxonomy term id(s).

Ie: mysearch/\[key\]/\[terms\]|My custom search label.

---
Tags: 7, taxonomy-terms, search, uri
---


# Question
Title: Image slideshow with onclick on thumbnails
I am theming a node. I Want the images in the node to be displayed as below:

when I click on the second image second image should be loaded , when I click on third image third image should be loaded and so on.

How can I do this.

# Answer
Used Simple javascript:

Below is the code in my node--contenttype.tpl.php

```
<div style = "width:500px; scrolling:no">
 <?php $listing_images = get_listing_images($node->nid);
    if(!empty($listing_images)){
   $first_uri = get_first_image($node->nid);
   $first_filename = end(explode("/",$first_uri));
       $first_image = str_replace("public://",             "http://localhost/drupal7/sites/default/files/",$first_uri);
 ?>
<img src="<?php echo $first_image;?>" width="500" height="375" id = "listing_main"><br/>
<?php foreach($listing_images as &$limage){
     $filename = end(explode("/",$limage));
     $image = str_replace("public://", "http://localhost/drupal7/sites/default/files/",$limage);
?>
<img src ="<?php echo $image;?>" width="59" height="44" onClick="javascript:getsrc('listing_main','<?php echo $image;?>')">
<?php
 }
 }?>
 </div>
  <?php function get_listing_images($node){
   $uri = array();
   $result = db_query("SELECT  uri FROM {file_managed} WHERE fid in (select field_listing_image_fid FROM {field_data_field_listing_image} WHERE entity_id = :entity_id) order by timestamp desc", array(':entity_id' => $node));

  while($record = $result->fetchObject()){
  $uri[] = $record->uri;
  }
   return $uri;
  }

  function get_first_image($node){
     $result = db_query("SELECT  uri FROM {file_managed} WHERE fid in (select field_listing_image_fid FROM {field_data_field_listing_image} WHERE entity_id = :entity_id) order by timestamp desc", array(':entity_id' => $node));
     $record = $result->fetchObject();
     $uri = $record->uri;

     return $uri;
     }
     ?>

```

Below is the code in javascript file:

```
function getsrc(id,image){
  document.getElementById(id).src = image;
 }

```
> 0 votes

---
Tags: 7
---


# Question
Title: Count content types which have taxonomy term
I have a content type where a taxonomy term is associated to it . I would like to know how could i count the number of content types by taxonomy term ?

# Answer
You can use the following snippet, to get count of nodes by passing the term id

```
<?php
  $tids = array(1); //An array of term IDs to match.
  $nodes = taxonomy_select_nodes($tids);
  echo count($nodes) ;
?>

```

Edit:

You can use views to achieve this, check this similar question . It explains an example
> 1 votes

# Answer
You can try Term Node Count module. Though it is still for Drupal 6, but you will find the Drupal 7 compatible version from this discussion.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: %1 doesn't get converted to taxonomy name when overriding title
When using `Content: Nid` as a contextual filter for *"**Content**"* (node) type views, I can check *"**Override title**"* and use `%1`, and the node id will be converted to the real node title when displaying this title. (For example, I can type "Gallery of %1", and it will be converted to "Gallery of Blablabla".)

When I create a view for showing *"**Taxonomy Terms**"*, set "*Taxonomy term: Term ID*" as a contextual filter, check *"**Override title**"*, and use `%1` the same way I did for "Content", the taxonomy id doesn't get converted to the real name of the term! (so for example "term is %1" gets converted to "term is 261", which is not the expected result)

Why, and how can I get around this problem? I'd like to override the title and use the taxonomy term name.

# Answer
> 4 votes
It works for me with Drupal 7.

What I did was enabling the validation criteria, set the validator to *Taxonomy term*, and the type of the filter value to *Term ID*.

When I visit http://example.com/programming-languages I get the list of all the taxonomy terms terms for the "Programming languages" vocabulary.

When I visit http://example.com/programming-languages/20, I get a page using the overridden title.

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


title: Style a menu inside a specific block

text:
# Question
Title: Style a menu inside a specific block
I've created one menu to be placed on the left column and with context it will be repeated on the footer too. The difference is that the footer menu has to be already expanded and show all the child.

I can use this code below to make it as expanded

```
function mytheme_menu_link_alter(&$item, $menu) {
    if($item['menu_name'] == 'menu-about-us')
    {
        $item['expanded'] = 1;
    }
}

```

How do I targer the menu in the footer? How should I use the function `mytheme_preprocess_block(&$variables)` ?

Thanks in advance.

# Answer
> 1 votes
What your after is the following...

```
context_active_contexts()

```

http://api.drupalize.me/api/drupal/function/context\_active\_contexts/7

Example:

```
if (module_exists('context')) {
    $active_contexts = array_keys(context_active_contexts());
    if (in_array('SOMETHING', $active_contexts)) {
       //...
    }
}

```

---
Tags: routes, blocks, theming
---


title: Show Related Terms Block Not Nodes

text:
# Question
Title: Show Related Terms Block Not Nodes
Hello i have been trying for many a moon to create this View and i cant go on any longer its destrying my life (honest)

I want to show Related Terms (not content) on my taxonomy/term/\* page. Example.

White Setter and Black Setter are both in a dogs vocabulary. I have 'related' them via the taxonomy/term/***/edit-term page.

I want to create a block view that will show Black Setter on the White Setter page and vica versa. I have tried every relationship and every argument with no success at all. Does anyone know if this is possible to make?

Relationships Taxonomy: Related terms Arguments Taxonomy: Term ID

Thanks

Before i post i see that i have asked ths on other peoples posts (and one of mine) they where never resolved. People keep talking about adding nodes in the view but i was wanting to use a term View.

# Answer
It's not really hard:

1. Create a new taxonomy view.
2. Add an argument: `Taxonomy: Term ID`. If argument is not present, provide a default argument: `Taxonomy Term ID from URL`. Check the `Load default argument from term page` checkbox.
3. Add a relationship: `Taxonomy: Related terms`.
4. Finally, add a field: `Taxonomy: Term`. Use the `Related term` relationship, and check the `Link this field to its taxonomy term page` option.
5. Don't forget to create the block display.

Here's a view export: https://gist.github.com/4016927
> 1 votes

# Answer
As your requirement is to create a block that will show Black Setter on the White Setter page and vica versa, there is another simple way to achieve this. The function taxonomy\_get\_related() will do this.

Create a block with input format as php and use above function to print related terms by passing current page term id. Then assign the block to particular region. The following snippet will works,

for eg:

```
 <?php
    $termid = arg(2);
    $terms = taxonomy_get_related($termid, $key = 'tid');
    //print_r($terms);
    foreach($terms as $term){

       $link = url('taxonomy/term/'.$term->tid);
       echo '<a href="'.$link.'">'.$term->name.'</a>';
     }
  ?>

```
> 5 votes

---
Tags: 6, views
---


# Question
Title: What API function do I use for redirecting to external URLs?
When writing a module, for redirecting to Drupal paths, one uses `drupal_goto`.

Is there some API function that I should use for redirecting to external pages? Or is setting the `Location` with `drupal_set_header` the way to go?

PS I have to do some processing on the request; `mod_rewrite`/`mod_alias` on Apache-level or the Drupal `Path redirect` module, don't solve my problem.

# Answer
You should use drupal\_goto() for internal and external redirections.

Use 'external' option for external redirections: `drupal_goto($url, array('external' => TRUE));`

> drupal\_goto($path = '', array $options = array(), $http\_response\_code = 302)

**$options: (optional) An associative array of additional options, with the following elements:**

* **'query'**: An array of query key/value-pairs (without any URL-encoding) to append to the URL.
* **'fragment'**: A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.
* **'absolute'**: Defaults to FALSE. Whether to force the output to be an absolute link (beginning with http:). Useful for links that will be displayed outside the site, such as in an RSS feed.
* **'alias'**: Defaults to FALSE. Whether the given path is a URL alias already.
* **'external'**: Whether the given path is an external URL.
* **'language'**: An optional language object. If the path being linked to is internal to the site, $options\['language'\] is used to look up the alias for the URL. If $options\['language'\] is omitted, the global $language\_url will be used.
* **'https'**: Whether this URL should point to a secure location. If not defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can only be enforced when the variable 'https' is set to TRUE.
* **'base\_url'**: Only used internally, to modify the base URL when a language dependent URL requires so.
* **'prefix'**: Only used internally, to modify the path when a language dependent URL requires so.
* **'script'**: The script filename in Drupal's root directory to use when clean URLs are disabled, such as 'index.php'. Defaults to an empty string, as most modern web servers automatically find 'index.php'. If clean URLs are disabled, the value of $path is appended as query parameter 'q' to $options\['script'\] in the returned URL. When deploying Drupal on a web server that cannot be configured to automatically find index.php, then hook\_url\_outbound\_alter() can be implemented to force this value to 'index.php'.
* **'entity\_type'**: The entity type of the object that called url(). Only set if url() is invoked by entity\_uri().
* **'entity'**: The entity object (such as a node) for which the URL is being generated. Only set if url() is invoked by entity\_uri().

**$http\_response\_code:** (optional) The HTTP status code to use for the redirection, defaults to 302. The valid values for 3xx redirection status codes are defined in RFC 2616 and the draft for the new HTTP status codes:

301: Moved Permanently (the recommended value for most redirects).

302: Found (default in Drupal and PHP, sometimes used for spamming search engines).

303: See Other.

304: Not Modified.

305: Use Proxy.

307: Temporary Redirect.

# Drupal 8

Drupal 8 has removed drupal\_goto function, for redirect to external URL see this answer for the question: How do I redirect to an external URL?.
> 26 votes

---
Tags: 7, redirection
---


title: How to add Views into a Panels page

text:
# Question
Title: How to add Views into a Panels page
I have 2 views with contextual filter, they work well stand alone.

Now I want to include those two views into a panel (called eg. trypane/ ) and pass to it the contextual filter for the views it includes (eg. 19)

So I create a new content, panel, and i've added those two views. But when i call the panel (trypane/19) simply it doesn't work.

The infos for the views included are:

```
Using display Master.
1 items displayed.
Without pager.
Sending arguments.
Using arguments: %2

```

and a similar description for the second.

What's wrong with my setup?

# Answer
You should create a views display of type "Content pane".

Then ideally configure it to take arguments from context, and specify that the view requires a node id (or whatever you actually need). This will make the view much smarter, for example allowing Panels to hide the view from the UI all together when on a non node page.

Then add the new content panes to the page. You should be asked for which node you want to use as the source for the nid. Usually there will only be one, and you can continue without changing any settings.

And your view will now show up.
> 2 votes

---
Tags: panels, views
---


title: Lightbox2 doesn't appear in the page

text:
# Question
Title: Lightbox2 doesn't appear in the page
I want to add Lightbox2 from http://lokeshdhakar.com/projects/lightbox2/ to my page, but following instructions (adding a JavaScript, and a CSS file) doesn't work.

I thought I did all correctly, but when I click on the image, it doesn't show any popup.
What's wrong with it?

# Answer
There's also a Lightbox2 Drupal Module that integrates with various other modules. And you don't need to update your Drupal's jQuery.

Here's the documentation since I don't really know how you're intending to use Lightbox2 on your website.
> 1 votes

---
Tags: 7
---


# Question
Title: Converting date into unix timestamp not giving expected result
Basically I was trying to get age from date of birth, for which I am using `Computed Field` module.

Following code was used:

```
$isoArray = explode ( '-', substr($entity->field_dob1[0]['value'],0,10));
$bdayunix = mktime ( 00, 00, 00, (int)$isoArray[1], (int)$isoArray[2], (int)$isoArray[0]);

$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$entity_field[0]['value'] = $age;

```

When I checked the code, I found that this part of code is not giving the correct result:

```
 $isoArray = explode ( '-', substr($entity->field_dob1[0]['value'],0,10));
 $bdayunix = mktime ( 00, 00, 00, (int)$isoArray[1], (int)$isoArray[2], (int)$isoArray[0]);

```

I can say that because when I try to convert **$bdayunix** into date,whatever the date of birth is, I always get the result 1999.

```
ie; $dob = date("Y",$bdayunix ); always gives result:1999.

```

Could you please tell me where I am going wrong? Is this problem of Computed field module or I am doing some mistake in my code ?

(Date format in users bday field is yyyy-mm-dd and I have tried all types: Date, DateISO format and Date Unix timestamp).

Thank you in advance.

# Answer
I found the solution .

If we select Field type as Date(Unix Timestamp) then `$entity->field_dob1[0]['value']` will return unix timestamp value which can be directly used.

So if anyone in same requirement can use the following code:

```
$bdayunix = $entity->field_date_of_birth['und'][0]['value'];
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$entity_field[0]['value'] = $age;

```

PS: Dont forget to select field type as Date(Unix Timestamp).
> 0 votes

---
Tags: datetime, entities
---


# Question
Title: Menu add item or edit item not available for users with admin rights
I'm working on a Drupal core 6.26 website and I'm unable to debug or find an answer for this problem.

I have a group of users, let's call it GroupTest that has permissions enabled for administer menu.

When trying to edit a menu item or add a menu item with a user from GroupTest group, the add item / edit item form (actually just the fieldset Menu settings) is hidden by an inline "display: none;" style. The only thing visible is the save button.

However, this doesn't happen when I'm using the admin (1) user. The form is displayed just fine.

I've tried different approaches to debug this, looking for hook\_form\_alter in custom modules/themes that might be modifying this, even for javascript code that would hide the form.

Any help or hint would be greatly appreciated.

# Answer
> 1 votes
Do you have any custom/forked modules installed on the site? Themes?

Try changing the theme; if it works with another theme (let's say Bartik) then the problem is somewhere in your theme.

If the above doesn't work, clone the site and start disabling the modules one by one; eventually you will find the one which is causing the problem.

---
Tags: routes, forms
---


title: Split Menu in two

text:
# Question
Title: Split Menu in two
I'm trying to create a page where the main menu will be a horizontal nav structure, but split into two groups of links so that I can have a logo in the centre of the nav menu and half the links either side of it.

Has anyone done this with Drupal? Any ideas on how it would be done?

# Answer
> 1 votes
Just create a link to the home page, move it to the middle and then grab it with CSS to show the logo as background image, hide text and space out the left and right sides.

Check out also Menu Icons which allows you to upload images for menu items.

---
Tags: 7, routes, navigation
---


# Question
Title: Problem displaying second level navigation in menu block
I have something strange happening with a drupal 7 site i'm working on. I have a main navigation menu which also provides navigation via a menu block for all second level pages. this works fine - i have an additional main navigation menu which can be toggled with the main navigation at the user's discretion -this is also working fine. however, displaying the second menu in a menu block is proving difficult. i have matched the settings for both menu blocks so they are associated with the correct menus respectively, and yet on the second menu block, it will only display if the top-level links are included. so, if i want to display the second-level only, regardless of setting the maximum depth, nothing shows up. if i include the top-level and set the depth to include children, that works fine; the top level and second level are there. however i need to exclude the top level and this doesn't seem a simple task.

is this a common problem, or has anyone experienced anything similar??

Neil

# Answer
> 1 votes
I don't sure if you are using only Drupal standard menu system or any menu modules. If not, check Menu Block module.

This module gives you lot of options to place menu in blocks, including just some parts of a certain menu as I think you want.

For example, you define a block that shows the second-level menu of the current fist-level active item.

---
Tags: 7, routes, blocks, navigation
---


# Question
Title: Print comment form inside node's page instead of a link to comment page
How can I print comment form inside node's page instead of a link to comment page (Drupal 6) ?

# Answer
> 1 votes
You can set that under "Comment settings" on the edit page of your content type.

---
Tags: 6, theming, forms, comments
---


# Question
Title: how to change widget type of title field in content type Drupal 7
I am trying to change the widget type for title field in content type (currently it's a text field as default). Now I want to change to node reference.

# Answer
> 1 votes
i think, it is better to remove the original field 'title' and create new field for node reference type, use:

```
<?php
    function your_module_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'your_node_form'){
            $form['title']['#access'] = FALSE;
        }
    }

?>

```

# Answer
> 1 votes
There is also http://drupal.org/project/auto\_entitylabel which can help you hide the title and automatically fill the title field using tokens.

See this video for a howto http://codekarate.com/daily-dose-of-drupal/drupal-7-automatic-entity-label-module.

# Answer
> 0 votes
You can't use a widget as such; the title isn't a field, it's a property of the node entity type and doesn't have the capacity to use a field widget (without some serious messing about).

Also I don't think a node reference would work quite as you expect for this. The value saved by a node reference field is the ID of the referenced node, not the title, so you would simply be creating nodes whose titles are the IDs of other nodes.

You could probably look at implementing your own autocomplete for the title field if you really want to do this, but it will involve some code. Have a look at the form examples in the Examples module for some inspiration, there's some related stuff in there.

# Answer
> 0 votes
That is not possible. But you can try this:

1. Add an other fileld with the required widget type.
2. Use the automatic node title module to set the title to the value of the extra field. The module does give you the possibility to hide the original title field alltogether.

---
Tags: nodes
---


# Question
Title: Include a third party library using namespaces, dependencies
I made a library to access to the Taleo data ( https://github.com/Polzme/Taleo ). I tried to follow the best practice to do it. It's using composer ( http://getcomposer.org/ ) to resolve dependencies to Monolog and Guzzle.

Now, the big question is, how to use my library 'Taleo' in a Drupal module ?

I tried with xautoload ( http://drupal.org/project/xautoload ) and composer\_autoload ( http://drupal.org/project/composer\_autoload ) without success.

I also tried to include the file 'vendor/autoload.php', but it doesn't works (and it works well in the demo.php file: https://github.com/Polzme/Taleo/blob/master/demo.php)

Before including each file manually, I would like to know if there is a working solution available for Drupal 7.

Thanks!

# Answer
> 3 votes
It is indeed possible with xautoload.

Here is some explanation what initially went wrong: https://gist.github.com/4018045

As a general guide:

```
function hook_libraries_info() {
  return array(
    'Taleo' => array(
      'name' => 'Taleo PHP Library',
      'xautoload' => function($api) {
        // $api already knows the library path.
        // 'src' is relative to that.
        $api->namespaceRoot('Taleo', 'src');
      },
    ),
  );
}

```

The $api object is explained here: http://drupalcode.org/project/xautoload.git/blob/refs/heads/7.x-2.x:/lib/InjectedAPI/hookXautoload.php

---
Tags: 7, theming
---


# Question
Title: How to remove Input format from comment form?
I used following code to create a module to remove input format from comment forms, but it doesn't work. Is there anything I'm missing or another way to do this ?

```
<?php
function comment_custom_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'comment_form') {
    foreach ($form['comment_filter']['format'] as $i => $filter) {
      if (is_int($i) && !$filter['#type']) {
        $form['comment_filter']['format'][$i]['#value'] = '';
        $form['comment_filter']['format'] = '';
        unset($form['preview']);
        unset($form['_author']);
      }
    }
  }
}
?>

```

# Answer
```
Administer > Site Configuration > Input Formats

```

Click configure for each of the formats, and edit which roles can see which format.

You can also look at Better Formats.

> Set the default format per role. Set the default format per content type. Control allowed formats per content type. Hide format tips. Hide more format tips link. Hide format selection for nodes, comments, and blocks seperately, forcing the default to be used. Expand the selection fieldset by default. Disable the expand/collapse of the selection fieldset. Set selection fieldset title. Set more format tips link text. Set default formats for nodes and comments separately. Sensible defaults and fail overs for ease of use. Works with CCK textareas. Works with Panels comment form. i18n module support for user defined strings

.

Also if you want to hide it completely you can also unset the filter form element in your form alter but I don't think it is the right way to do it.

```
unset($form['comment_filter']['format']);

```

**NOTE: If you do so you will loose out on text processing and checks which drupal makes to make sure the html is safe.**

This should also work

```
$form['comment_filter']['format']['#access'] = FALSE;

```

This will make sure the format is not accessing to anyone.

---

Try this

```
function modulename_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'comment_form') {
  $form['comment_filter']['format']['#access'] = FALSE;
 }
}

```
> 3 votes

---
Tags: 6, input-formats
---


# Question
Title: Best practice for third-party PHP class-based library
I am currently working on a module that requires a third-party PHP library, which is essentially a single PHP class. Normally, I would place it in an includes/ subdirectory and add

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

```

to my .info file and let the Drupal 7 class auto loader do its thing when I do a `$foo = new Foo()`.

I have permission, though, to release this module to the public and would rather not include the library with the module. I am well aware about the complications regarding licensing, but for the sake of this question, I would like to ignore it.

There is a similar question, How do I include a PHP library?, but I don't really think this answers my dilema.

This answers to this question essentially say to use the Libraries API, but every single module that I have found that uses this just does a`libraries_get_path()` to get the basepath (and includes fallback path when it isn't available) and then does a `require` or `include` with some error checking (or not). All do something like:

```
if (!class_exists('Foo')) {
  $path = function_exists('libraries_get_path') ?
    libraries_get_path('foo') : 'sites/all/libraries/foo';
  if (!include($path . '/Foo.php')) {
      // handle this error
  }
}

```

In this case, the Libraries API isn't really doing anything. I don't see the advantage to using this, over the old method of asking users to download a copy and place it in the module folder itself. And, there is still the issue that the module developer *still* needs to *manually* do the load with `include`/`require`. For example, the Facebook module just loads the library in a `hook_init` and the HTML Purifier module has an internal function to check-and-load every time the library is needed.

This may be a *widespread* practice, but it doesn't seem like a *best* practice.

Should my module take the initiative and declare a `hook_libraries_info` so I can use `libraries_load('foo')`? This, too, seems odd.

# Answer
> 6 votes
Branch 2.x of the Libraries API module allows developers to define, through hook\_libraries\_info(), or a .info file for the library, the following information (see libraries.api):

* The dependencies of the library
* The version with which the library is compatible, for each of the dependencies
* The list of the files that needs to be loaded (CSS, JavaScript, or PHP files)

The list of files that needs to be loaded is used to load those files, when the library is required. This means that your module doesn't need to load CSS, and JavaScript files with `drupal_add_css()`, or `drupal_add_js()`, as that is already done from the Libraries API module. Loading the dependencies is a task done from the Libraries API module, without the calling module doing anything.

All the module does is using the following code, for loading a library. (See Using Libraries API 2.x (as module-developer).)

```
// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

```

If you just need to detect if a library is present, the module should use code similar to the following one.

```
if (($library = libraries_detect($name)) && !empty($library['installed'])) {
  // The library is installed.
}
else {
  $error = $library['error'];
  $error_message = $library['error message'];
}

```

Between the properties `hook_libraries_info()` can return, there is also `'download url'`, which is not actually used, not even in the branch 3.x. Probably it will be used in future, or a third-party modules could hook into the Libraries API module, and download the libraries that are requested, but missing.

# Answer
> 5 votes
After a decent amount of digging, I am still unconvinced about what the best practice is. Inspired by the PHPMailer module, I am offering this for class based PHP libraries:

```
function foo_registry_files_alter (&$files, $modules)
{
  if (!class_exists('Foo')) {
    $library_path = function_exists('libraries_get_path') ?
      libraries_get_path('foo') : 'sites/all/libraries/foo';

    $files[$library_path . '/Foo.php'] = array(
      'module' => 'foo',
      'weight' => 0,
    );
  }
}

```

This uses hook\_registry\_files\_alter to check for a class's existence, and if not found, add a file to the class registry (the equivalent to a `files[] = ...` line in a modules .info file). Then, classes defined in foo.php will be available with the autoloader, so there is no need to explicitly load the file before using the class.

This also creates a soft requirement on the Libraries API, and will use it if available, otherwise use a reasonable default.

Adding some checks via a hook\_requirements to make sure the file exists, that the autoloader finds the class, version check, etc, is also be a good idea.

It is also worth noting that an autoload approach for the Libraries API is being discussed in the issue queue.

# Answer
> 2 votes
**In short:** If you are planning to release module to public and the (third party) library is not GPL'd, you will need to use Libraries as a dependency or ask users to download these files manually (but you will not be able to autoload it from .info file)

**In little longer:**

The reason why we need Libraries module is basically licensing. No matter you use that module or not, you are including that file in some way.

Well I think you didn't find good examples for such libraries-shipped-with-the -module cases. Check out SMTP module and it comes with the necessary classes as it's in GPL. (.info file blob).

Also see simplehtmldom module which just include the file but nothing else.

Where Libraries module comes handy is that, you can ask users to upload the file anywhere they want. It's not obvious that users will upload it to sites/all/libraries folder. It could be sites/example.com/libraries or something like that. Libraries module can help you to focus on your actual work by doing the directory discovery stuff for you.

For custom modules that I develop for my clients, I usually include files in module folder and use require\_once or .info file entry depending on use of the library.

Also, licensing problems are not the only reason to use Libraries module. What if the third party library has rapid release cycles and your module is minimally developed ? If you include it in the module, you will have to make a new release everytime. You will not want to have a release 7.x-1.99 which is much similar to 7.x-1.0 i guess.

# Answer
> 2 votes
It seems the major problem is the autoload.

You can use libraries module plus xautoload module.

Then in your own module, you do

```
function mymodule_libraries_info() {

  return array(
    'mymodule-test-lib' => array(
      'name' => 'My test library',
      ..
      'xautoload' => function($api) {
        // Register a namespace with PSR-0 root in <library dir>/lib/
        // Note: $api already knows the library directory.
        // Note: We could omit the 'lib', as this is the default value.
        $api->namespaceRoot('XALib\TestNamespace', 'lib');
      },
    ),
  );
}

```

This is explained in more detail here:
xautoload.api.php
More about the $api argument.

Note: You can also write your own "handlers", to implement more exotic old-school patterns beyond PSR-0 or PEAR. If you need help with that, post an issue on the xautoload queue.

Note: There is more than one way to register your library namespaces. This one is the easiest, if you want the namespaces to be registered in every request.

---
Tags: 7, theming
---


# Question
Title: How can I hide a certain warning message showing to users?
I would like to hide the following warning message from users when they submit a web form. I know when this warning message shows up and don't really need to fix it but just want to hide it from users.

```
warning: trim() expects parameter 1 to be string, array given in /public_html/sites/all/modules/phpmailer/includes/phpmailer.drupal.inc on line 33.

```

I tried Disable message module but it's only for the Drupal system error message. Is there anyway to hide a certain warning message just like above?

# Answer
> 0 votes
On admin/settings/error-reporting, you set where the messages generated by PHP warnings/errors are shown.

When you select *Write errors to the log and to the screen* for *Error reporting*, such errors are shown on the screen, and saved in the database table containing the error messages; when you select *Write errors to the log*, the errors are not shown on the screen.

drupal\_error\_handler() is the error handler set by Drupal in \_drupal\_bootstrap\_full(). The code that shows the message, and/or saves them in the database is the following one.

```
// Force display of error messages in update.php.
if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
  drupal_set_message($entry, 'error');
}

watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);

```

}

# Answer
> 2 votes
You need to include `ini_set( 'display_errors','0');` in your setting.php file in drupal site.

See more about error reporting http://php.net/manual/en/function.error-reporting.php

// Reporting E\_NOTICE can be good too (to report uninitialized // variables or catch variable name misspellings ...)

```
ini_set( 'display_errors','0');

```

---
Tags: 6
---


# Question
Title: Internal Server Error with Multiple Tags
When creating a Drupal view that filters based on multiple tags, I'm getting the following error when I click preview:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /admin/structure/views/view/breakfast\_things/preview/page\_1/ajax StatusText: Internal Server Error ResponseText:

And the following error when I hit save:

> Notice: Undefined property: Drupal\views\ManyToOneHelper::$query in Drupal\views\ManyToOneHelper-\>add\_filter() (line 312 of core/modules/views/lib/Drupal/views/ManyToOneHelper.php).

Here is a screenshot of my page (this was after I clicked save)

If I keep everything the same but only use one tag, like eggs, then it works perfectly fine. Anyone know what's wrong here? I'm trying to create a view that will show all posts about eggs, spam, and other breakfast items.

# Answer
> 0 votes
SK , When you choose tag field in sort criteria, you will get two options Dropdown and Autocomplete. Choose Dropdown . This should fix your problem.

---
Tags: 7, views
---


title: Altering markup of language switcher

text:
# Question
Title: Altering markup of language switcher
I want to lightly alter the language switcher block's markup by adding additional classes, among others "clearfix" to clear the floats. I cannot however pin down where the markup is created.

This link http://drupal.org/node/1369090 (last post) suggests using template.php but again, I cannot see how I would alter the wrapper div's markup.

Is there any way to achieve this?

# Answer
> 7 votes
In D7, the language switcher block is created in `locale_block_view()`:

```
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

```

You can use `hook_block_view_alter()` to modify the markup of the block.

If you want modify the output of the links, you can override the `theme_links()` function in your theme using `THEME_links__locale_block()` in the template.php file.

---
Tags: theming, i18n-l10n
---


# Question
Title: How can I allow users to cancel their accounts without requiring e-mail confirmation?
In Drupal 7, users can cancel their accounts from the account settings page. However, by default this requires e-mail confirmation.

There is an option "Require e-mail verification when a visitor creates an account" but no option "Do not require e-mail verification when a user cancels an account."

Is there some way to allow users to simply cancel their accounts while logged in rather than requiring them to verify the cancellation via e-mail?

# Answer
> 12 votes
The behaviour seems to be hard-coded into the `user_cancel_confirm_form_submit()`, which sends a message to the user if they don't have the `administer users` permission.

I can't see any pretty way of getting round it really, but there is something you can do.

First you need to set an undocumented variable called `user_mail_cancel_confirm_notify` to `FALSE`. I'd recommend using Drush to do it:

```
drush vset user_mail_cancel_confirm_notify FALSE

```

But you can do it in PHP if you need to:

```
variable_set('user_mail_cancel_confirm_notify', FALSE);

```

That will stop the `_user_mail_notify()` function from sending the cancellation confirmation email.

Next, you need to hook into the form submission for the cancellation confirm form, and force-cancel the account (otherwise it would be waiting for the user to click the cancellation link in the email you've just stopped):

```
function MYMODULE_form_user_cancel_confirm_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_user_cancel_form_submit';
}

function MYMODULE_user_cancel_form_submit(&$form, &$form_state) {
  // Rather than negating the complex access expression from the original form we can
  // just make the change in the else portion

  global $user;
  $account = $form_state['values']['_account'];
  if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) {
    // Account has already been cancelled by the system.
  }
  else {
    // Cancel the account
    user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);
  }
}

```

I haven't tested any of that but after reading the functions involved in the user module I'm pretty sure it will work.

# Answer
> 1 votes
The answer above is good but you gain control using your custom form\_submit, just copy the code above and change default submit by yours.

```
function MYMODULE_form_user_cancel_confirm_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][0]= 'MYMODULE_user_cancel_form_submit';
}

function MYMODULE_user_cancel_form_submit(&$form, &$form_state) {
  //Copy the code from user_cancel_confirm_form_submit() at user.pages.inc
}

```

It is a little more tricky because you have to avoid using core's default validation, but you gain control over what you want to show to your users. Because the other solution doesn't stop the messages of "email was sent" to be shown

---
Tags: 7, users
---


# Question
Title: Do I use Content Type creator to create new modules?
I read the Drupal 7 tutorial on creating modules. I did fine from code and the example. Got the basics.

Then I read about creating a new content type with fields. I have ubercart and it had a product type, so I am kind of lost. Other modules have their own content types with fields.

Say I wanted to track an inventory at the most basic level. I want to know the item number and description, and on hand amount. Nothing fancy.

Do I create a table to hold that data in the drupal database? somewhere else? Do I create a field with the content type additions?

Not sure what do to. Thanks for help.

# Answer
---

edit

After a quick google search I found this. Might be useful -http://drupal.org/project/merci- (couldn't add more links)

---

I'm sure there is already a module you can download that does something similar to what you'd like to do, but if not then you should probably start like this.

Install the ctools and views module

Things that can be done without code (Drupal creates the tables in the database for you)

* Create content type
* Add necessary fields to it (sku, description, amount remaining)
* Create some nodes of your content type with sample data in order to build/test your module as you go
* Create a view to display nodes of your new content type

Now for the code

You also mentioned übercart, are you currently using it? If so you can just add fields to that content type and track those with your module and not have to deal with creating content types and views, because ubercart does all of that for you.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: is autopostback available in jQuery or Ajax
for Drupal 6 sites. I know that autopostback is an ASP.NET piece of functionality. Is there something similar that I can apply in Drupal 6. I want to apply autopostback to a drop-down select list in a view.

All I have found so far is this piece of code:

document.getElementById('mytextbox').AutoPostBack = true;

# Answer
```
<select id="autosubmit" name="autosubmit" class="autosubmit">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

```

**jQuery**

```
$(document).ready(function () {
  $(".autosubmit").each(function (index) {
    $(this).change(function () {
      // write your custom trigger here.
    })
  });
});

```
> 1 votes

---
Tags: javascript, entities
---


# Question
Title: How to display a create node form together with a referenced node of a different type
I'm using a content type for Clients and another content type for Tasks. Each client has many tasks and each task belongs to one client. Both types are connected by a reference field defined for the Task content type that points to a Client node.

I know how to display a Client's information together with a list of all Tasks for that client. I'm using a view in a block that is parameterized with the Client node ID. That was easy.

However, in order to create a new Task for a Client, I need to **display the Client's information together with the create new task form**.

Is there any way I can do that in Drupal 7?

# Answer
If you need to put that info in a block near the form, you can create your custom hook like

```
function mymodule_menu(){
  $items = array();
  $items['mynode/add/%/%'] = array(
      'title' => t('Create content'),
  'description' => 'Calls to a drupal_get_form',
  'access callback' => 'user_access',
  'page callback' => 'my_function',
  'page arguments' => array(2,3),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
 );

 return $items;
}

```

So now you have a page called /mynode/$type/$id\_user

In that page you can render the form of that content type using drupal\_get\_form() and returning it rendered. Now in the blocks config you can add your block view to the pages called /mynode/mytype/\* , getting the user id argument from the url will let you render that view with the user data.
> 0 votes

---
Tags: forms, nodes, entities
---


# Question
Title: commerce drupal 7 cache module suggestion
Any experiences of suggestion about what cache module to use in with a commerce store? I have been researching about it and I cannot find any suggestions or problems that you can face when using Drupal commerce with caching.

# Answer
> 2 votes
Have you tried to use Authcache module with memcache module

http://drupal.org/project/authcache

Also check Entity cache for Drupal Commerce module

http://drupal.org/node/1588814/release

---
Tags: 7, caching, performance, commerce
---


# Question
Title: How to add recurring to all product by default monthly?
I am using ubercart and uc\_recurring module and Drupal6. I wanted to add monthly payments to all products by default. How can i do this ?

I added a rule to add the data to the DB using php code while creating new product

```
$data = array(
  'pfid' => ' ',
  'nid' => $node->nid,
  'fid' => 'recurring',
  'description'=>'When this product is purchased, add a fee for the same amount as the product selling price charged first after 0 days and every 1 months after that 99 times.',
);
drupal_write_record('uc_product_features', $data);

$q = "SELECT pfid FROM {uc_product_features} WHERE fid= '%s' AND nid = %d";
$result = db_query($q, 'recurring', $node->nid);
$num = db_result($result);

$data2 = array(
  'pfid' => $num,
  'model' => ' pro',
  'fee_amount' => ' ',
  'initial_charge'=>'0 days',
 'regular_interval'=>'1 months',
  'number_intervals'=>100,
);
drupal_write_record('uc_recurring_product', $data2);

```

Still recurring is not working? When i go to the path /node/\*/edit/features and simply submit the form without updating any fields it works?

Am I missing anything?

# Answer
> 0 votes
Finally its solved by changing the code in rules

```
<?php
    //Recurring
    $data = array(
   'pfid' => ' ',
   'nid' => $node->nid,
   'fid' => 'recurring',
   'description'=>'When this product is purchased, add a fee for the same amount as the product selling price charged first after 0 days and every 1 months after that 99 times.',
     );
   drupal_write_record('uc_product_features', $data);

   $q = "SELECT pfid FROM {uc_product_features} WHERE fid= '%s' AND nid = %d";
   $result = db_query($q, 'recurring', $node->nid);
   $num = db_result($result);

  // Build the recurring fee's product object.
   $product->pfid = $num; //pfid
   $product->model = '';
   $product->fee_amount = 0.000;
   $product->initial_charge = '0 days';
   $product->regular_interval = '1 months';
   // If number intervals is negative, it means that it's unlimited intervals.
   $product->number_intervals = 100;
   $product->nid = $node->nid;

   uc_recurring_product_feature_save($product);
 ?>

```

I am not sure whether its a proper way..

---
Tags: ubercart
---


title: Add more rows to the title field

text:
# Question
Title: Add more rows to the title field
The title field only has 1 row for text. I want to expand it vertically with more rows.

How to add more rows?

# Answer
> 1 votes
```
/**
 * hook_form_FORM_ID_alter() function implementation.
 * @param unknown_type $form
 * @param unknown_type $form_state

 */
function yourmodule_form_article_node_form_alter(&$form, &$form_state) {
    // Add your own function to the array of validation callbacks
    $form['title'] = array(
            '#type' => 'textarea',
            '#title' => 'Title1',
            '#required' => 1,
    );
    return $form;
}

```

I have created for article node type. You can use same for other node typw also. I have used hook\_form\_FORM\_ID\_alter() API function.

---
Tags: entities
---


# Question
Title: How can I customize a menu to be intuitive for my users: show user name, have dropdown items
I am looking to create a user menu. The menu when not logged in should have two options: 1. create account 2. sign in. These items will be displayed in-line.

Once logged in, I want the menu to have two options: 1. account name 2. sign out

When logged in the "account name" menu item will have a drop down with menu items linking to the various user tabs present in the user backend.

Information: I am working with a theme I downloaded. The main menu has a fairly extensive dropdown function but I do not know how it is doing it. If I could figure that out then I could apply that to the user menu for the function I want.

The reason I want this done: I had a potential customer loose interest and leave my site because he could not figure out where he could download his files from. So I figured I needed to create a easy to understand user menu.

Thanks for your help!

Drupal 7 link to my website: sonikloops.com

# Answer
> 5 votes
This can be easily done with the available following contributed modules.

* Create menus from Admin UI, and restrict the visibility by Menu Per Role module. Here, you might like to to show the menus *Create Account* and *Sign In* only to anonymous (not logged in) users.
* You can use the Menu Token module, if you wish to show username as menu. You'll need to install the Token module and the Ctools module in order to do this. This can be done in following way:

1. Create a menu link in your User menu using Admin UI by visiting `http://yoursite.url/admin/structure/menu/manage/user-menu`.
    2. In the link title you input the user name. The following will replace the `[current-user:name]` with the username of the logged in user. You can even use other fields, under the "Menu Token Options" \> "Replacement Patterns".
    3. The output of the above:
    As admin:
    As an authenticated user:
* For the dropdown feature of the menu, you can use the DHTML Menu or the Superfish menu.

Hope that helps. Please feel free to ask questions.

---
Tags: routes, users
---


title: how to use Drupal menu system AND OR

text:
# Question
Title: how to use Drupal menu system AND OR
I'm trying to display all content labeled under my taxonomy terms with ids 1 and 3. Both terms work fine so that If I point my browser to www.mysite/?q=taxonomy/term/1 or www.mysite/?q=taxonomy/term/3

But trying to use drupals built-in AND/OR feature using the urls below gives me a "Page not Found" error.

www.mysite/?q=taxonomy/term/1+3 www.mysite/?q=taxonomy/term/1,3

Any ideas? thanks

# Answer
> 2 votes
Install the views module and then go to `?q=admin/structure/views`.

You will find a disabled view created by default named "Taxonomy term" with an ID equal to taxonomy\_term.

Enable this view; it will override the default taxonomy page. Configure the view to match your case, and click save.

---
Tags: taxonomy-terms
---


title: Cron runs async?

text:
# Question
Title: Cron runs async?
Since the cron is ran during the users' pageload, does it run async, or does it block the request until it's finished?

In the latter case, what would the best practice be not to have the user wait too long. I want to do a few `user_delete` calls on each cron run (as many as possible without blocking the site). I saw Drupal has some kind of a queue-ing mechanism, but I didn't see any doc about how it's used.

# Answer
> 2 votes
This depends on the way you setup and you are running the cron.

If you enabled the `Run cron every` field at `Admin -> Config -> Cron (admin/config/system/cron)` then the cron will be triggered by opening pages on the site, and *yes* it will affect the page load of visitors.

However, it is recommended to disable the cron on that page and setup a cron task on your server. You can read the article here on how to do that correctly. In this case it is not blocking the site directly, but it will still, partially, affect the visitors who are using the site at the time of execution.
This is because often the cron will look for updates and perform other resource-intensive tasks and there will simply be less server resources available.
For this reason if you need to run the cron only once-twice daily, you run it usually during the night or some other time when you don't have many visitors.

Lastly, check Elysia Cron which allows you to finetune what exactly is executed and how often - it calls selectively `hook_cron()` of the modules you have on the site.

---
Tags: 7, cron
---


# Question
Title: custom module: drupal_add_js and drupal_add_css do not work after form validation?
I have created a custom module that changes the layout & adds extra functionality to one of my content type creation and edit forms.

It works beautifully and as expected apart from when I submit the form with, for example, a blank node title or any other required fields.

The page is reloaded as expected with the error message, the form modifications are loaded from the module (field #prefix, #suffix etc..) but the css and the js are not loaded.

Here is the code I have:

```
/**
* Implementation of HOOK_form_alter()
*/
function mymodule_entry_form_modify_form_alter(&$form, $form_state, $form_id) {

  // 1.ENTRY FORM
  if ($form_id == 'entry_node_form') {

  // here were some form field modifications i removed

/* 1.3 LAYOUT - ADD JAVASCRIPT FILES
 * Add .js files
 */
// add jquery script before calling it
drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/jquery.fixheight.js');
// call the script
drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/mymodule_entry_form_modify.js');

/* 1.4 LAYOUT - ADD CSS FILES
 * Add .css files
 */
drupal_add_css(drupal_get_path('module', 'mymodule') . '/includes/css/mymodule_entry_form_modify.css');

 }
}

```

Can anyone explain why this happens?

# Answer
I don't use D7, but I believe you should be using #attached and it should fix your issue.
> 8 votes

# Answer
You have to add to your `hook_form_alter` a new validation callbacks:

```
/**
* Implementation of HOOK_form_alter()
*/
function mymodule_entry_form_modify_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_entry_form_modify_form_alter-submit_callback';
}

```

In your new validation callback, add your drupal\_add\_css().

```
function mymodule_entry_form_modify_form_alter-submit_callback($form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/jquery.fixheight.js');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/mymodule_entry_form_modify.js');
  drupal_add_css(drupal_get_path('module', 'mymodule') . '/includes/css/mymodule_entry_form_modify.css');
}

```

And this is a general rule: add your `drupal_add_css` in the validation callback of all your forms if they need a dedicated style even if a `drupal_set_form` have been triggered.
> 3 votes

---
Tags: 7, forms, javascript
---


# Question
Title: How to show views filters on a block or page
I have a view with exposed filters to customers.

I want the exposed filters on a separate page/block and views result on a separate page.

How to do this.

# Answer
Choose exposed form in block to yes in views advanced settings, Then you can find your exposed form block in block listing page and can configure to any page or region
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to change the look and feel of exposed filters in a block
I have view which has exposed filters. I have configured those filters to block. But now I want to change the look and feel of the exposed filters .

How to do this.

# Answer
If you want more control over your exposed form template, you an write a template file for it. This article will help you to define template file.

Otherwise you can change the appearance with css, And you can use form alter in case of alter any elements.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Add node programmatically including CCK field
I'm pulling content from a web service and adding the nodes programmatically. Here is my code so far:

```
foreach($content as $key => $value) {
    $node = new stdClass();
    $node->title =  $value['title'];
    $node->type = $field_map['type'][$value['type']];   // Use remote type as key in field map array to get local type
    node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
    $node->language = (isset($value['language'])) ? $value['language'] : LANGUAGE_NONE;
    $node->uid = $GLOBALS["user"]->uid;
    $node->status = $value['status']; //(1 or 0): published or not
    $node->promote = $value['promote']; //(1 or 0): promoted to front page
    $node->comment = $value['comment']; //2 = comments on, 1 = comments off
    $node->created = $value['created'];
    $node->changed = $value['changed'];
    $node->sticky = $value['sticky'];
    $node->translate = $value['translate'];
    $node->uuid = $value['uuid'];

    $node = node_submit($node); // Prepare node for saving
    node_save($node);
}

```

The example I'm following says to add cck fields like this:

```
// Entity reference field
    $node->field_customer_nid[$node->language][] = array(
        'target_id' => $form_state['values']['entity id'],
        'target_type' => 'node',
    );

```

I'm having difficulty because my CCK fields will vary depending on the content type that is being pulled form the web service. My fields are stored in the following format:

```
$value['field_publish_date']

```

How could I go about adding the fields to my node?

# Answer
Okay, figured this one out. If you don't know the name of the fields until runtime then you can assign the field name using curly braces when assigning to the stdClass e.g:

```
  $node->{$field_name}[$node->language][$j]['value'] = $field_value['value'];

```
> 0 votes

# Answer
First I would recommend using this type of structure for crating nodes progmatically

```
$node = new stdClass();
$node->type = 'story';
node_object_prepare($node);

```

If you're worried bout the content type being an issue use a switch statement by passing the content type in:

```
swicth($field_map['type'][$value['type']]){
  case 'story': //populate fields of story type;
    break;
  case 'page': //populate fields of page type;
    break;
}

```

Also if you are using a web service to import nodes I would suggest that you use the Feeds module http://drupal.org/project/feeds rather than creating them manually. I'm speaking from experience .
> 1 votes

---
Tags: entities, nodes
---


title: Commerce: 1 product but N prices

text:
# Question
Title: Commerce: 1 product but N prices
I have a problem/question.

My client need to sell one product but the price of this product (digital, so no shipping cost or other) is based on a field in a table. Explain: X categories and Y places. Each combination of X per Y return a different price for the only 1 product.

How can I set the price of this product at "checkout" ? In node Z (where categories is 1 and places is 2, for example) I can write the correct cost value (via preprocess\_node, or template function or other), but in the cart?

# Answer
You have two options.

1. You can create one product for each combonation of X and Y and have those as values on the product. If you reference all the products on the node, commerce can turn the value of X and Y into a dropdown which will trigger an ajax update, changing the other data for the product like this price.
2. The other options if you don't want to create a product for each combonation (my preferred solution), would be to create a pricing rule, custom code is probably needed here, to calculate and set the unit price on the line item based on X/Y data.
> 1 votes

---
Tags: 7, commerce
---