# Question
Title: How to call a function in template.php through ajax from a page?
I have a button in drupal page template. When user clicks on that it will write the text in the text box to a text file.

I have written a function for that in template.php file. I want to pass the value in text box to the function using ajax. But how can I do it? What url should i give in javascript ajax function?

# Answer
I would recommend using the Ajax Framework in Drupal 7 core: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7.

You will need to create a callback through hook\_menu which will return the html you want to load.

See the examples module for how to do this. The two functions show adding a link and using the 'use-ajax' class and creating a link using a render array: http://drupalcode.org/project/examples.git/blob/refs/heads/7.x-1.x:/ajax\_example/ajax\_example\_misc.inc

They both link to 'ajax\_link\_callback' which calls the other function ajax\_link\_response().

'ajax\_link\_callback' is defined in hook menu like so:

```
 180   // A menu callback is required when using ajax outside of the Form API.
 181   $items['ajax_link_callback'] = array(
 182     'page callback' => 'ajax_link_response',
 183     'access callback' => 'user_access',
 184     'access arguments' => array('access content'),
 185     'type' => MENU_CALLBACK,
 186     'file' => 'ajax_example_misc.inc',
 187   );

```
> 2 votes

# Answer
You can't do such a thing.

You need to create a callback - a url you can call from the JavaScript and define a function that returns a response.

See `hook_menu` for detail.
> 1 votes

---
Tags: 7, ajax, theming
---


# Question
Title: Drupal authentication for a non-Drupal script
I have a non-Drupal PHP script I would like to put on a D7 Drupal site, but I would like it to be available only to users who have logged in via Drupal. What are the best/easiest ways to do this? It's my script, so I can change it any way I want, embed it in a module, a PHP-capable field, etc.

To be specific, it's a signup sheet system that uses form submissions, using files (not the db) to store the data.

# Answer
> 3 votes
You can wire up your script via a hook\_menu, and instead of returning the output to render via Drupal, you can print it directly and exit at the bottom of the function. The submission handler would do the same thing, but drupal\_goto() at the end.

That said, this is a moderately bad idea for the long run.

A better solution would be to use Webforms. Webforms are really easy to make, get stored in the database, and can be exported to Excel. I wouldn't be surprised if there is webform hook available so you could do your filesystem thing, too.

Another option is to use the Forms API to make your form w/ your custom validation and submission handlers.

# Answer
> 2 votes
Another option, though you might find it to be too much work, is to roll your functionality up in a module. With a `hook_menu` call back, you can have the the module run any php code you define. So you would get both your Drupal authentication and your PHP functionality all in one go :)

**Edit** You would have to create a permission hook in order to limit access to it.

---
Tags: users
---


# Question
Title: How to create a link on a field in a custom template file
I created a custom tpl file for the teaser of a node. To print the fields i use render() eg:

```
render($content['field_subtitle']);

```

This all works fine but i would like for example that the rendered output of field\_subtitle has a link to the actual node.

My workaround for the moment is to do something like this,

```
<a href="<?php print $node_url; ?>">
   <?php print render($content['field_product_subtitle']); ?>
</a>

```

This works but produces some nasty looking html with div's inside the . So i was wondering if you could just add a parameter to the render function that produces a link to the node?

# Answer
You will want to use a preprocess function in your theme's template.php file, so that you can manipulate the element's attributes before it is rendered.

For example, if you wanted to link a particular field to the node's page, you could implement template\_preprocess\_field() as such:

```
function THEMENAME_preprocess_field(&$vars) {

  $items = $vars['items'];
  $node = $vars['element']['#object'];

  $path = 'node/'.$node->nid;

  if($vars['element']['#field_name'] == 'TARGET_FIELD_NAME'){
    foreach($vars['items'] as $key=>$item){
      $vars['items'][$key]['#markup'] = l($item['#markup'], $path);
    }
  }
}

```

the l() function is a structured way to build a link within the Drupal API. In this example I have assumed that the field is only allowing plain text, but if your field allows HTML, you can pass extra variables to the l() function that will allow that.

You can access other node data in the $node variable I created, such as the node type, published status, etc. If you want to investigate all the variables available to you in this (or any) preprocess function or template, I would suggest installing the Devel module and printing out the variable you are interested in with the kpr() function. For example, you could add the following code to the preprocess function I created above:

```
kpr($vars);

```

and you would be able to see all of the data available for use in that function in an easy-to-read format.
> 4 votes

# Answer
As a follow up to @Lance's answer, you have access to the `$node` object in your template file so it would be as easy as:

```
$title = $node->field_product_subtitle[$node->language][0]['value'];
print l($title, "node/$node->nid");

```

That will print the whole `<a>` tag with the correct URL alias for the node, with your custom field value inside.
> 2 votes

# Answer
Use the l() function. Example:

```
print l(t($content['field_product_subtitle']), 'node/'. $node->nid));

```
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal Views: Taxonomy Stripes for Calendar
I've got a bit of an issue with taxonomy stripes on Calendar.
If I wanted to define colour stripes for Content Types, I get this choice:

Simple. I just choose the type and add a colour.
However, I want to do it for Taxonomy. So I choose Taxonomy in the Stripes menu:

I successfully link it to the relevant taxonomy field, but I see no option for colour choice?

I'm using the most recent stable version of the calendar and the views modules.

How do I do this?
Is there another way?

# Answer
> 1 votes
Use the latest development snapshot. See http://drupal.org/node/1392306#comment-5581466 for the patch.

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


# Question
Title: Any flexible customizable theme for display configuration via panels?
Recently, I have been trying to design pages using panels and mini-panels. I followed some tutorial online, but the method used was a bit questionable. Since I am a newbie at this, I crashed my system beyond all repair, lol, but I managed to export valuable configuration and reload it on a fresh install. So, I am happy enough with that...

I have been playing with changing colors under Bartik, but honestly, that won't be enough...

I am looking for a flexible theme that will allows me to easily design the layout of pages from scratch using panels (most preferably). Ideally, I should be able to configure colors and fonts easily and the basic template should be simple and elegant. I want to load my own pictures to customize it (i.e., no preloaded pictures or they should be made removable).

Basically, the site is about sharing tips. Users will be able to put comments and vote for posts made by an editor. Nothing crazy.

Does anyone have a good recommendation to make for Drupal 7? Is there any such thing as a newbie-proof template? Thanks.

# Answer
> 0 votes
After doing more reading and video watching, I got to understand that some specific themes have been created for the Panels Everywhere module. It does not really make sense to use panels without panels everywhere. I am using Precision.

The Omega theme and Zen theme suggested in other answers are indeed powerful themes, but they don't integrate with panels. These are based on blocks, regions and zones.

# Answer
> 2 votes
I still very new to the Panels module and theming in general but I have really enjoyed the Zen base theme.

I think it would have been confusing as a 'first' theme, but if you've been playing with Bartik and other common Drupal themes I think you'll love Zen.

The support, documentation and standardization surrounding the project is very impressive.

I should note though you need to be comfortable designing with CSS. It's very 'clean' out of the box.

# Answer
> 2 votes
If - as I read from your question - you prefer a solution that's highly configurable through the admin-interface as opposed to coded through the theme, Omega theme in combination with Omega Tools, Delta and Context modules might be what you are looking for.

---
Tags: 7, theming
---


# Question
Title: Call-time pass-by-reference has been deprecated in phptemplate_init() with specific theme
I installed the last Drupal 7 Stack from BitNami. It seems to work correctly with the default themes but when I switch to the twitter\_bootstrap theme (7.x-2.x-dev at http://drupal.org/project/twitter\_bootstrap ) the "Call-time pass-by-reference has been deprecated in phptemplate\_init()" appears.

I look at the phptemplate.engine file but can't pinpoint the issue at line 14 (**\_include\_once DRUPAL\_ROOT . '/' . $file;\_**)

```
<?php

/**
 * @file
 * Handles integration of PHP templates with the Drupal theme system.
 */

/**
 * Implements hook_init().
 */
function phptemplate_init($template) {
  $file = dirname($template->filename) . '/template.php';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

/**
 * Implements hook_theme().
 */
function phptemplate_theme($existing, $type, $theme, $path) {
  $templates = drupal_find_theme_functions($existing, array($theme));
  $templates += drupal_find_theme_templates($existing, '.tpl.php', $path);
  return $templates;
}

```

# Answer
The indications to solve this issue are available at: http://drupal.org/node/1423518
> 1 votes

---
Tags: theming, social-network
---


title: How to find a mails $mailkey

text:
# Question
Title: How to find a mails $mailkey
I'm trying to theme a couple of different mails generated by notifications using the mimemail module. Is there a reliable method to find a mails mailkey for use in a template?

# Answer
> 0 votes
The easiest way to check the mailkey is if you look at the source code of the mail you received. The body-tag has a class with the mailkey. At least if you use the default template.

---
Tags: 6, emails
---


# Question
Title: Rule to autopopulate node reference field and redirect after content creation
I'm trying to make a rule so that when a node of content type X is created, a node of content type Y is also created and is automatically populated with a nodereference field to the nid of content type X that was created. Then the user should be redirected to the edit form of the node of content type Y that they just created.

My rules configuration looks like this right now:

**Event:** After saving new content

**Condition:** Content is of type X

**Actions:**

* Create a new entity of content type Y
* Set a data value: set the node reference field on new node of content type Y nid of new node of content type X
* Page redirect: URL: \[entity-created:edit-url\]

Everything works as expected except the redirect (which I thought would be the easiest part). Both nodes get created and the node reference field is set correctly. But I get a page not found error with the following messages:

> Notice: Undefined property: stdClass::$nid in node\_tokens() (line 112 of /web/xxxxxx/www/modules/node/node.tokens.inc).
>
> "content type X" "title of new content of type x" was successfully created
>
> The requested page "/node//edit" could not be found.

I've also tried node/\[entity-created:nid\]/edit for the page redirect. Same exact problem. I have no idea why it's not plugging in the nid of the new node of content type Y in between node/\*/edit.

# Answer
> 3 votes
Basically you need to create another event right after "create entity" which immediately saves the new entity before you move on to the redirect rule.

See also http://groups.drupal.org/node/204558#comment-688188.

# Answer
> 1 votes
After setting the data value, also choose the action "Save entity" action and remove the page redirect action which is not yet needed.

Next

Create another rule that has:

Event "After Saving new Content"

Condition: content of type y

Action: Page redirect -\> \[node:edit-url\]

When you are done with both rules, you can set the weights of the rules so that one runs before the other. So set your rule to weight: -2 and then set the new rule to weight: -1 and save them. At the bottom of the page click on settings and you will see a drop down of values for the weights.

---
Tags: 7, rules, tokens
---


title: Mysql Strict Mode?

text:
# Question
Title: Mysql Strict Mode?
Is Drupal 7 running in mysql strict mode?

I am getting errors such as:

* Invalid datetime format: 1292

Is there a way to turn this off?

# Answer
Yes it is. It is documented on this issue: http://drupal.org/node/303054
> 1 votes

---
Tags: 7, database
---


# Question
Title: Embed a node form with default values in drupal 7
How do I embed a node form and set some default values in that form in Drupal 7?

I understand that I can use this:

```
 $form = node_add('product_plan');
 print drupal_render($form);

```

That prints the form on to the page just fine, but I need help understanding how I can add default values. In Drupal 6, I would normally do this:

```
 function module_nodetype_form_embed( $property )
 {
     global $user;

    $node = new stdClass();
    $node->type = 'node_type';
    $node->uid = $user->uid;

    // Hidden through form alter
    $node->field_node_reference[0]['nid'] = $property->nid;
    node_object_prepare( $node );

    return drupal_get_form( 'node_type_node_form', $node );

 }

```

So how can I get the same functionality in Drupal 7

# Answer
> 1 votes
I got it to work with this in D7:

In your custom module write this function:

```
function module_nodetype_form_embed( $property )
 {
 global $user;

$node = new stdClass();
$node->type = 'node_type';
$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
// Hidden through form alter
$node->field_node_reference['und'][0]['target_id'] = $property->nid;
node_object_prepare( $node );

return drupal_get_form( 'node_type_node_form', $node );

 }

```

When you want to embed this form in a node template, do this:

```
/* I'm assuming that your $property argument from the function
   is the $node page that you are embedding into. */

$form = module_nodetype_form_embed($node);
print drupal_render($form);

```

The only problem that I'm encountering is that the validation errors are not showing up on the initial submit if the user didn't fill in the form properly...BUT if you try and submit with invalid values more than once, the error messages show up. Weird....

# Answer
> 1 votes
If you are using a 'select list' widget for the node reference you can do this:

```
$form = node_add('product_plan');
$form['FIELD_NAME'][$form['language']['#value']]['#value'] = 'NID';
return drupal_render($form);

```

'autocomplete' widget would look like:

```
$form = node_add('product_plan');
$element['#default_value'] = 'NID';
$form['FIELD_NAME'][$form['language']['#value']][0]['nid']['#value'] = node_reference_autocomplete_value($element, FALSE, '');
return drupal_render($form);

```

---
Tags: 7, nodes, forms
---


# Question
Title: Edit content created by users with the same role
Is there any module that would allow me to edit/delete nodes created by users with the same role I have?

# Answer
I would approach this by grouping users with organic groups module instead of by role. Roles are only for defining access level, not for making groups of users.
> 3 votes

# Answer
I believe rules is capable of doing that. Something like:

On node edit: If user has role: author role (any other role except authenticated user) OR admin role

let it edit. Else, redirect with message.

Of course, this is just the logic outline. You'd have to do the actual PHP code for this to work. ^^
> 1 votes

# Answer
First of all, the module that provides the content type (via an implementation of hook\_node\_info()) is the only authority over who may edit content of that content type. If the module chooses not to consult role based permissions, the node access table or other modules, there is not much you can do about it (except for hacking the module). A module that meets the requirements you described can therefore (in general) not exist.

If you restrict your question to those content types, that are provided by the node module (i.e. the ones that are created via the Durpal UI): every authenticated user has the role "authenticated user". A module that meets the requirements you described would therefore grant all authenticated users write access to all nodes created by an authenticated user. This can be done by granting the permission *edit any $type content* to the role *authenticated user* for every content type `$type`.

This has the effect that authenticated users can also edit content created by anonymous users. I do not think this is a problem, because an authenticated user can always become an anonymous user, simply by logging out.

What remains do be done is granting anonymous users the permission to edit content of other anonymous users (yes, they are a role as well), but not content created by authenticated users. This is only a problem when you allow anonymous user to create content.
> 0 votes

---
Tags: 7, users
---


title: no-indexing a views page

text:
# Question
Title: no-indexing a views page
Im using D7 and views 3 and I cant seem to find a solid answer on how to do this or if its possible but I created a page in views and I wanted to no-index the page, I dont see any options in views to do it so im wondering if this is possible and if so how can I go about doing this.

Any help is appreciated it.

EDIT\**

Here is a function I managed to come up with however it something is making it not work. Does anyone have any suggestions?

```
function noindex_taxonomy(&$head_elements) {
  if (arg(0) == 'taxonomy' && arg(2) == 104 || arg(0) == 'taxonomy' && arg(2) == 103 || arg(0) == 'taxonomy' && arg(2) == 108) {
    $head_elements['noindex'] = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
  }
}

```

# Answer
I was able to achiveve this by putting my function into my template.tpl.php file

```
function loans_html_head_alter(&$head_elements) {

/*Url inside the view*/ $siteurls = drupal_get_path_alias();

if (arg(0)== 'taxonomy' && $siteurls == 'taxonomy/term/104/latest') {
    $head_elements['noindex'] = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
  }
}

```
> 0 votes

# Answer
There is not any option in views module to add metatags. but you can add metatags to any url of your site by other drupal metatag modules. See How to define Meta tags on Views?.
> 1 votes

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


# Question
Title: What's the difference between globals $base_root and $base_url
Can't seem to find the difference between these. D6 is what I need to know, but would love to know how those looks into 7 and even 8.

# Answer
> 7 votes
`$base_root` is:

> The root URL of the host, excluding the path.

e.g. http://localhost

`$base_url` is:

> The base URL of the drupal installation.

again, e.g. http://localhost

The only situation I can think of where these would be different is if your Drupal installation is in a sub-folder of the web root. In that case `$base_url` would also contain the sub-folder in the path, e.g. http://localhost/drupal

The descriptions in the documentation are exactly the same for both across versions 6, 7 and 8.

---
Tags: 6
---


# Question
Title: Overwrite the title for a particular taxonomy page
Can anyone help me on how to overwrite the particular taxonomy page title in Drupal 7?

Let us say I have 4 or more taxonomy page. I need the page title to for 3 pages and not for 1 page. If my url is http://localhost/drupal/companies/* the title should be overwritten as "Hello"; if the url is http://localhost/drupal/technology/* the default page title should appear.

# Answer
It is easily done with the Taxonomy Title module.
It adds a "Term page heading" field for terms. Simply edit your term and you'll see.
> 2 votes

# Answer
The TVI module lets you pick a view for each term. Then in the view you can decide to show a title or not.
> 0 votes

---
Tags: 7, views, uri
---


# Question
Title: Is there a way to make a body field automatically become the first comment on a node?
Im on d7, I want my body field (or any textfield attached to a content type really) to automatically become the first comment on its node. Any suggestions?

# Answer
Without coding, I'd go for the module Rules : You can create action that are triggered after certain events, under certain conditions. In your case you can try to create a rule like this one :

* Event : When a Node is Created
* Conditions : You probably want to filter the node type maybe ?
* Action : Create an entity
    + Select Comment as your entity type
    + Node referencing the comment : Use the available token "node" (the newly created node that triggered your rule)
    + Comment body : Use the available token node:body

And you're done .. 0 code, 1 module, 2 mins to setup your rule :-)
> 2 votes

---
Tags: 7, nodes, entities, comments
---


title: Drupal 7 db_query using CAST

text:
# Question
Title: Drupal 7 db_query using CAST
Does Drupal 7's DB API support SQL's CAST function? I have a varchar with numbers in it that I'm trying to convert to integers for proper sorting. Here's my statement:

```
$images = db_query('SELECT filename, caption FROM {iha_captions}
WHERE uid = :uid ORDER BY CAST(weight AS INT) ASC', array(':uid' => $userid));

```

And here is the error I get:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INT) ASC' at line 1: SELECT filename, caption FROM {iha\_captions} WHERE uid = :uid ORDER BY CAST(weight AS INT) ASC; Array ( \[:uid\] =\> 2814 ) in iha\_search\_profile()

It then causes a cascade of SQL failures in Drupal's session and cache queries. Is `CAST` supported, or am I doing it wrong?

# Answer
It's not a Drupal error; it comes from the MySQL engine about CAST using:

> The type can be one of the following values:
> BINARY\[(N)\]
> CHAR\[(N)\]
> DATE
> DATETIME
> DECIMAL\[(M\[,D\])\]
> SIGNED \[INTEGER\]
> TIME
> UNSIGNED \[INTEGER\]

You cannot use `INT`; it should be `SIGNED`, `UNSIGNED` or `DECIMAL`.
> 2 votes

# Answer
It's not a Drupal error it's a MySQL error. `CAST()` won't accept `INT` as a valid type but does give you a choice between `SIGNED` and `UNSIGNED` to cast to an integer type.

The following query runs fine for me in Drupal:

```
SELECT * FROM node ORDER BY CAST(nid AS UNSIGNED)

```
> 2 votes

---
Tags: 7, database
---


title: creating a block

text:
# Question
Title: creating a block
I created my first block in drupal. It basically creates a node create link for the places content type. But someone it doesn't work.

Can someone help me with this.

```
function custom_site_block($op = 'list', $delta = 0, $edit = array()) {
$blocks = array();
if ($op == "list") {
    // Generate listing of blocks from this module, for the admin/block page

$blocks['create_place'] = array(
    'info' => t('Create a place'),
    'cache' => BLOCK_CACHE_GLOBAL,
);
}
else {

    $form = array();
    $form['#action'] = url('node/add/place');
    $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Create a place'),
    );

}
 return $blocks;
}

```

# Answer
```
function custom_site_block($op = 'list', $delta = 0, $edit = array()) {
  $blocks = array();

  switch ($op) {

    case 'list':

      $blocks['create_place']['info'] = t('Create a place');
      $blocks['create_place']['cache'] = BLOCK_CACHE_GLOBAL;

      return $blocks;

    case 'view':

      switch ($delta) {

        case 'create_place':

          $blocks['subject'] = t('My First Block');
          $blocks['content'] = l(t('Create a place'),'node/add/place');

          return $blocks;
      }
  }
}

```
> 0 votes

# Answer
You should be using the menu system to do this. Go to 'admin/structure/menu' and add a menu and a menu item with the link above. This will automatically create a block.
> 0 votes

---
Tags: blocks
---


# Question
Title: Is there a module that simply adds an 'add more' AJAX CCK field to a node form?
Drupal 7:

So I want to have this type of functionality:

The user needs to be able to add an unlimited, or up to a certain value of cck fields to the node edit form.

Basically, we want to create tutorials, and then add dynamic 'steps' via ajax. (because the amount of steps will always constantly change)

An example would be the poll module.

# Answer
You can set any field to allow more than one value on the same node. But if you need some kind of a group of fields, which you want to add dynamically, then I would suggest you to have a look at the Field Group module.
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: Unwanted / duplicated temporary css files if CSS Optimization is enabled
I'm experiencing the duplicate CSS issue mentioned in drupal.org #830382: Unwanted / duplicated temporary css files if CSS Optimization is enabled. In one of my production sites I have about 335 CSS files consuming 3.2M. While this is not a big deal at the moment but certainly not saner to let it grow as such. The site is relatively small and using not more than 10 CSS file. The issue link referred above doesn't seem to have any direction. I would like to hear from the experts here to fix it. Thanks in advance.

# Answer
> 5 votes
I think your problem is about aggregate css files. The issue you give is unrelated. Each page may need a different aggregate CSS file (even in D7, it's much better than it was in D6). It results in hundreds of CSS files as you may state.

Nothing to worry about. Unused file will be deleted automatically. I can't suggest you to use Advagg module because it is only for D6 now, but take a look to have an idea about aggregate files actually work (and how they *should* work).

# Answer
> 0 votes
335 does sound like rather a lot... I wonder if it is a sum of CSS files which have been used?

Try clear your cache to make sure CSS files are being automatically deleted. You should see them all disappear and then gradually be rebuilt as pages are requested which required different CSS files.

If they are not being deleted it might be worth checking file permissions to ensure Drupal has permission to delete them once they are no longer needed.

---
Tags: 7, theming, performance, files
---


# Question
Title: Field API, Field Attach API, Field Instance API, Field CRUD API OR Schema API?
I'm in my final semester for my degree in Computer Science, and we've been tasked with creating a project management system using Drupal. I thought this was great at first, we easily created a proof of concept using already built modules. And then I attempted to code.

Basic Idea: We thought about defining our own schema for entities, but the company needs a dynamic way of defining and sharing fields (like the entity / field API already does), so we decided to stick with the built in Entity / Field API.

Entity types would be things like request, project, task, etc...

Fields would be things like select lists, questions for the request form (that could be transferred over to a project once the request was approved), and other text fields needed for the project.

I was thinking that using the field API to start with some of the needed select lists (that the admin can add/update/delete default values to) would work fine - because I defined these with the UI thinking man this is easy. Select lists such as legacy company, products, and other short lists related to telecom. **But I cannot programmatically define a select list field with predefined values. How can I do this?** I've googled, and searched, and followed this great article, but it does not delve much into select lists, and how to define default values, or any of the $options available for a select list \[and neither do the API docs, they do not tell what values should be used, or even the default widget types\].

Am I going about this all wrong? Maybe I should just create some good old crud classes and be done with it. The only problem with this is that it would be extremely difficult to make the system as dynamic as they want, or would it?

# Answer
Personally I wouldn't bother doing it yourself, Drupal has it all set up for you and it's just a matter of working out the format it wants data in and you can use all the goodness of the entity/field system.

The following function is one I use all the time. Given an existing entity type, field name and bundle it will produce the code you need to run to create said field instance:

```
function __export_field($entity_type, $field_name, $bundle_name) {
  $info_config = field_info_field($field_name);
  $info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
  unset($info_config['id']);
  unset($info_instance['id'], $info_instance['field_id']);
  include_once DRUPAL_ROOT . '/includes/utility.inc';
  $output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
  $output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
  drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
}

```

For example, if you have a field called `field_image` attached to the standard `article` content type, you would export both the field creation code, and field instance creation code with this:

```
__export_field('node', 'field_image', 'article');

```

The code prints out to the standard drupal message area and can just be copied and pasted to wherever you need it.

For your specific needs, the value list for a select widget is added in the `settings` part of the field array, under `allowed_values`:

```
$field = array(
  'translatable' => '0',
  'entity_types' => array(),
  'settings' => array(
    'allowed_values' => array(
      1 => 'First Choice',
      2 => 'Second Choice'
    )
  ),
  // etc...
);

```

If you haven't seen it already check out the Examples module, there's loads of example code in there to help with entity/field manipulation.
> 4 votes

---
Tags: entities
---


# Question
Title: Custom form from user registration form not showing new fields in D7
I am trying to build a new form from the user registration form and while the user reg parts are appearing the new fields are not. Any ideas? The code is below. I tried having the fields in the primary array level AND under the account parameter.

When the array prints out it shows the parameters are there. So I am having trouble figuring out why it is not working. I am used to doing this in Drupal 6. But in Drupal 7 it is not cooperating.

```
function custom_reg_company_registration() {
  return drupal_get_form('custom_reg_company_form');
}

function custom_reg_company_form($form, &$form_state) {
  $form = user_register_form($form, $form_state);

  $form['company_name'] = array(
    '#type' => 'textfield',
    '#title' => 'Company Name',
    '#maxlength' => 60,
    '#description' => 'The name of your company.',
    '#required' => 1,
    '#attributes' => array(
      'class' => array(0 => 'company_name'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['primary_phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Primary Phone',
    '#maxlength' => 30,
    '#description' => 'The primary phone number for your company.',
    '#required' => 1,
    '#attributes' => array(
      'class' => array(0 => 'primary_phone'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['secondary_phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Secondary Phone',
    '#maxlength' => 30,
    '#description' => 'The secondary phone number for your company.',
    '#required' => 0,
    '#attributes' => array(
      'class' => array(0 => 'secondary_phone'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['company_type'] = array(
    '#type' => 'radios',
    '#title' => 'Company Type',
    '#maxlength' => 30,
    '#description' => 'The type of company you are setting up.',
    '#required' => 1,
    '#default_value' => 0,
    '#weight' => -10,
    '#options' => array(
      0 => 'Carrier',
      1 => 'Broker & FF',
      2 => 'Shipper',
    ),
  );

  $form['#action'] = url('register/company');

  echo "<pre>" . print_r($form, true) . "</pre>";

  return $form;
}

```

# Answer
> 1 votes
`$form = user_register_form($form, $form_state);`

This line is strange and should probably be : `$form = drupal_get_form('user_register_form');`

Also, your function looks like a form\_alter hook, with the relevant parameters, but it won't be called because it isn't named correctly.

If you want to alter the registering form, you should use the 'your\_module\_user\_register\_form\_alter' syntax as shown here http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_form\_alter/7.

EDIT : This code is more standard, and also works :

```
function yourmodule_menu() {
  $items['stackform'] = array(
    'title' => 'Code Stack Exchange',
    'description' => 'Test SE',
    'page callback' => 'custom_reg_company_form',
    'access callback' => TRUE,
  );
}

function custom_reg_company_form() {
  $form = drupal_get_form('user_register_form');

  $form['company_name'] = array(
    '#type' => 'textfield',
    '#title' => 'Company Name',
    '#maxlength' => 60,
    '#description' => 'The name of your company.',
    '#required' => 1,
    '#attributes' => array(
      'class' => array(0 => 'company_name'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['primary_phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Primary Phone',
    '#maxlength' => 30,
    '#description' => 'The primary phone number for your company.',
    '#required' => 1,
    '#attributes' => array(
      'class' => array(0 => 'primary_phone'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['secondary_phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Secondary Phone',
    '#maxlength' => 30,
    '#description' => 'The secondary phone number for your company.',
    '#required' => 0,
    '#attributes' => array(
      'class' => array(0 => 'secondary_phone'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['company_type'] = array(
    '#type' => 'radios',
    '#title' => 'Company Type',
    '#maxlength' => 30,
    '#description' => 'The type of company you are setting up.',
    '#required' => 1,
    '#default_value' => 0,
    '#weight' => -10,
    '#options' => array(
      0 => 'Carrier',
      1 => 'Broker & FF',
      2 => 'Shipper',
    ),
  );

  $form['#action'] = url('register/company');
  return $form;
}

```

Note that both snippets work on a D7 install, mine is just better practice.

If your fields don't appear, it probably means some module is resetting the form AFTER your module's intervention. You can try to change your module's weight to prevent this and see what happens.

# Answer
> 2 votes
Is there a reason you need to use code? You could just add the fields to the user profile and check "required on registration" to make them show up during registration.

# Answer
> 1 votes
Have you tried clearing the cache? This code creates the form with the "Company Name" and other fields for me.

Is custom\_reg\_company\_registration() a callback from hook\_menu?

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


# Question
Title: Using hook_form_alter(), how do I write a multi-select field?
So I have a field that displays locations a list of multi-select locations.

The select has a name of `field_location`

I want to turn access to this off, and then rebuild the field with a limited list of locations that I will populate.

```
function rm_report_form_alter(&$form, &$form_state){
    if (arg(0) == 'node' && $form['form_id']['#value'] == 'c_node_form') {
        $form['field_location']['#access'] = FALSE;
    }
}

```

The problem: Not sure how to rewrite a multi-select field.

# Answer
I think you are searching for the #multiple attribute:

# multiple

Used by: select

Description: Indicates whether the user may select more than one item.

Values: TRUE or FALSE

```
<?php
return array(
  '#type' => 'select',
  '#title' => $title,
  '#default_value' => $value,
  '#options' => $options,
  '#description' => $description,
  '#multiple' => $multiple,
  '#size' => $multiple ? min(12, count($options)) : 0,
  '#weight' => -15,
);
?>

```
> 1 votes

# Answer
Not 100% sure what you try to accomplish. However the code should look more like this:

```
function myModule_form_formID_alter(&$form, &$form_state){
    if (arg(0) == 'node') {
        $form['formID']['field_location']['nid']['nid']['#access'] = FALSE;
    }
}

```

You can use the devel module and its dpm() statement, or even more powerful get Xdebug running on your dev machine to see the full structure of the data.
> 0 votes

---
Tags: 6, forms
---


# Question
Title: Create a separate view for each primary menu based on URL aliases in drupal 7
I have created a taxonomy menu in drupal 7. Let say the main menu has technology and market data.

1. Let say Technology has sub menu as security and security has test1 and hello as sub menus and so on.

```
-Technology       URl: http://localhost/drupal/taxonomy/term/1
     -- Security    URL: http://localhost/drupal/taxonomy/term/2
         --Test     URL: http://localhost/drupal/taxonomy/term/3
         --Hello    URL: http://localhost/drupal/taxonomy/term/4

```
2. Market data also has the same hierarchy.
3. These are the values I have set while creating the view

```
    Format:

      Unformatted list | Settings

      Show:Content | Teaser

    FILTER CRITERIA
      Content: Published (Yes)

      Content: Type (= Article)

      Content: Has taxonomy terms (with depth) (or Technology, ...) | Settings

    PAGE SETTINGS

      Path:/taxonomy/term/%

      Menu:No menu

      Access:Permission | View published content

    CONTEXTUAL FILTERS
      Content: Has taxonomy term ID (with depth)

```

After creating this view I am able to see the view in all pages (Technology,Security,test1,Hello) I am able to display article as mention in point 1.

Now I replaced the url with automaic url aliases and the url it generate the following URL.

```
        -Technology       URl: http://localhost/drupal/technology
             -- Security    URL: http://localhost/drupal/technology/security
                  --Test     URL: http://localhost/drupal/security/test
                  --Hello    URL: http://localhost/drupal/security/Hello

```

Now I replaced the view with following settings

```
     Format:

   Unformatted list | Settings

   Show:Content | Teaser

FILTER CRITERIA
   Content: Published (Yes)

   Content: Type (= Article)

   Content: Has taxonomy terms (with depth) (or Technology, ...) | Settings

 PAGE SETTINGS

   Path:/technology/%

   Menu:No menu

   Access:Permission | View published content

 CONTEXTUAL FILTERS
   Content: Has taxonomy term ID (with depth)

Within  Has taxonomy term ID (with depth) has the following settings:

     WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED
       Override title:    %1
     Specify validation criteria

      Validator

         Taxonomy Term

      Vocabularies

         Home Page Main Menu

      Filter value type

         Term name converted into ID

   I have selected the Transform dashes in URL to spaces in term name filter values also.

```

But the problem is I am not able to overwrite the taxonomy pages.

Can anyone help me what I have missed while creating the view.

# Answer
The reason for this problem has to do with how path aliases are handled. When the url is set to a page alias, Drupal translates the url into its actual url `taxonomy/term/tid` before it seeks the content that is to be displayed, such as your view definition whose path is still an alias. Since the view path doesn't match the URL, it is not selected to generate content. If you want a descriptive URL to work with the view path, you cannot use the path aliases.

I have a similar problem where I have converted hundreds of hierarchical taxonomy terms into a menu system with aliases using taxonomy menu. The aliases show up fine when I select a menu item, and set the View definition to `Taxonomy/term/%` but the views, of course, display the base URL instead of the alias. I have not explored a work-around yet. If you find anything, please post it here on your question.
> 0 votes

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


title: Errors when installing Token

text:
# Question
Title: Errors when installing Token
I installed the Token module, and it produced a bunch of errors. I accidentally navigated away from the page displaying the errors, and now I'm left wondering what future problems these errors might cause.

Is there any way to find out what went wrong with the install?

I am using Drupal 7.

# Answer
admin/reports/dblog will show you the last messages logged by Drupal. To see the menu, you need to enable the "Database logging" module, which is a core module present also in Drupal 6.
> 1 votes

# Answer
I have often seen errors generated when installing new modules that disappear of their own accord. It is quite possible that the newly enabled module is not finding or providing information it needs until the database is updated fully, or caches are cleared etc. Token is a very commonly used, stable module. If you have a problem you will continue to have error messages. Your best protection against any future problems is to establish a regular back-up routine for both your site code and database. If you have Drush and Git working on your development site, they make this process very simple, although if you are not familiar with them, there is a set-up and learning curve. If your in this for the long hauls, then it will be worth your while to set them up.
> 0 votes

---
Tags: tokens, installation
---


title: drush updatedb on multiple sites

text:
# Question
Title: drush updatedb on multiple sites
I have a multisite installation with common modules code (all modules are in sites/all/modules). When I update the modules, after that I need to update the database of each site with drush updatedb -l site.com It is a time consuming task to do this for each site. Is there a way to batch update the database in multiple sites?

Thanks

# Answer
> 4 votes
I believe drush v4.4 and above support `drush @sites updb`.

# Answer
> 6 votes
Here is a script I wrote for different time consuming tasks to run on a multisite installation

## The file has to be in your `sites` folder.

The script will loop through all folders (except `all` and `default`) to run the command choosen on every sites based on their `settings.php` file

```
#!/bin/bash

# Get all Drupal sites
sites=`find . -maxdepth 1 -type d -print | grep -v '/all$' | grep -v '/default$' | grep -v '\.$'`

echo "Choose the commande to execute : "
echo "1. update"
echo "2. put sites offline"
echo "3. put sites online"
echo "4. clear all cache"
echo "5. clear css+js cache"
echo "6. clear specific cache"
echo "7. install specific module"
echo "8. disable specific module"
echo -n "Input [1,2,3,4,5,6,7 or 8] ? "
read choice

if [ $choice -gt 6 ] ; then
  echo -n "Extension (module/theme) name ?"
  read ext
fi

# For each site, execute the command
for site in $sites
do
  echo ----------
  echo $site
  cd $site
  if [ $choice -eq 1 ] ; then
    drush updatedb
  elif [ $choice -eq 2 ] ; then
    drush vset --always-set maintenance_mode 1
  elif [ $choice -eq 3 ] ; then
    drush vset --always-set maintenance_mode 0
  elif [ $choice -eq 4 ] ; then
    drush cc all
  elif [ $choice -eq 5 ] ; then
    drush cc css+js
  elif [ $choice -eq 6 ] ; then
    drush cc
  elif [ $choice -eq 7 ] ; then
    drush pm-enable -y $ext
  elif [ $choice -eq 8 ] ; then
    drush pm-disable -y $ext
  fi
  cd ../
done

```

---
Tags: 7, drush
---


# Question
Title: Load a views block in a tpl file with his custom template
I have a custom tpl file for a node type, in this file i want to load a views block i created. This block has a custom template file to style the block itself.

I load the views block in the node template file with views\_embed\_view() but this just gives me the default html of the block and not the output of the blocks tpl file.

Is this possible with the views\_embed\_view() function or do i need to use some other function?

# Answer
> 0 votes
So to do this you just need to use the views\_embed\_view() function. I just had a typo in my template file.

So for someone who's looking for a way to do something similar:

```
<?php print views_embed_view('VIEW_NAME', 'DISPLAY_NAME', 'ARGUMENTS'); ?>

```

---
Tags: views, theming
---


title: Drupal 7.10 : views filters error

text:
# Question
Title: Drupal 7.10 : views filters error
i keep getting the following message on my exposed filters. Any ideas as to what i might have missed out when configuring the filters. I used the cck list (text) widget to compile options in each select list.

ps- i did not select the required option on the views filter options. For each filter i selected the expose filter option, the "is one of" option and the options i want to appear in the filters. I also have the Better formats module selected.

# Answer
This is a very common and very difficult to debug problem. It happens when there's an inconsistency between the cache version and the submitted version of a form; whatever the reason.

You're best bet would be to upgrade Views and Ctools (and perhaps BEF too) to the latest dev versions.

Also, one important thing to consider is wether or not you have custom code altering the form.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Can I filter entityFieldQuery results by Workbench moderation state?
I have the Workbench module and I want to look up nodes which have a specific workbench state with EntityFieldQuery.

I can get articles assigned to a user as follows:

```
$articles = new EntityFieldQuery();
$articles->entityCondition('entity_type', 'node')
         ->fieldCondition('field_moderating_user', 'uid', $user_id, '=');

```

Now I want to add a condition that only gets articles that have the state 'assigned'.

Any ideas?

# Answer
> 7 votes
An EntityFieldQuery can only filter based on fields associated with the entity by default, and since workbench moderation records are held in a custom table outside of the field system the standard query can't include a reference to them.

However, you can extend the query using tags and `hook_query_alter`, e.g.:

```
function MYMODULE_query_alter(QueryAlterableInterface $query) {
  // Only change the query if we have the required tag
  if ($query->hasTag('WorkbenchModerationAssigned')) {
    // Join the workbench moderation node history table
    $query->join('workbench_moderation_node_history', 'wmnh', 'wmnh.nid = n.nid');

    // Add the state and current conditions
    $query->condition('wmnh.state', 'assigned');
    $query->condition('wmnh.current', 1);
  }
}

```

You would then build up your EntityFieldQuery like this:

```
$articles = new EntityFieldQuery();
$articles->entityCondition('entity_type', 'node')
  ->fieldCondition('field_moderating_user', 'uid', $user_id, '=')
  ->addTag('WorkbenchModerationAssigned');

```

That's a very basic example which may need some changing, you might also want to join in the `workbench_moderation_states` table but it depends on your exact requirements.

**EDIT**

Just for a bit more info you can also use `hook_query_TAG_alter()` to do this in a more targeted manner:

```
function MYMODULE_query_WorkbenchModerationAssigned_alter(QueryAlterableInterface $query) {
  $query->join('workbench_moderation_node_history', 'wmnh', 'wmnh.nid = n.nid');
  // ...

```

---
Tags: entities
---


# Question
Title: How to create a fields on the users profile to allow them choose from a number of opens then order them based on preference
On the users profile, I need to add the ability for users to select from a number of options, then order them based on their preference.

e.g.

What are your favorite fruits?

Select from:

Apples

Bananas

Oranges

Grapes

Then I need the users to be be able to reorder them in terms of preference:

e.g.

Grapes

Bananas

Apples

Any thoughts on how to achieve this (existing modules)?

# Answer
If it's D7, user profiles are fieldable, so you've got what you want out of the box : add a field in admin/config/people/accounts/fields with a select wodget and you're done.

For the ordering, I think Draggable Views could be worth a look.
> 0 votes

---
Tags: 7, entities
---


title: Drupal 7: mark as offensive flag

text:
# Question
Title: Drupal 7: mark as offensive flag
I want to create a 'mark as offensive' flag for my site. However, I have no idea how to go about it. Is there a tutorial on the web that will guide me through the process?

# Answer
Also, checkout the Flag Abuse module.

> It works by giving a new permission for a role to be able to reset flags. If a role has this permission, the flag is changed to say 'Reset' instead of whatever the default text may be. When that user clicks this it resets all of the abuse flags on that object and makes to that it cannot be flagged as abuse anymore.
> 2 votes

# Answer
To do this you could use a popular module http://drupal.org/project/flag. There is also documentation here http://drupal.org/documentation/modules/flag.
> 3 votes

# Answer
http://www.youtube.com/watch?v=b5xieuVf01E&feature=BFa&list=PL1A89955CCEB73A09&lf=iv short and to the point
> 1 votes

---
Tags: 7, flags
---


# Question
Title: How to move a drupal 6 installation to a new server?
I backed up my files and database. uploaded files to new server, created and restored the database to the new server, edited the settings.php file. I navigate to the site, it pops up perfectly. I try to navigate to any other page and I get a 404 page not found error. What am I missing?

# Answer
Create a php.ini file and disable "register\_globals" on the 1and1 server.
> 0 votes

# Answer
Do you have `mod_rewrite` for Apache enabled/installed? If not, verify this is the case.

Also, ensure that your .htaccess file in your Drupal root is unchanged from the old server.

If you're on a Debian-based distribution, go to `/etc/apache2/mods-available` to verify that `rewrite.load` is present. Then go to `/etc/apache2/mods-enabled` to verify that rewrite.load is symlinked in that directory.

If you're on a RedHat distro like CentOS, then go to `/etc/httpd/modules` and look for `mod_rewrite.so`. Then, open up `/etc/httpd/conf/httpd.conf` and verify that this line is in there `LoadModule rewrite_module modules/mod_rewrite.so`.
> 3 votes

# Answer
Do you have the rewrite mode enable? If not, try enabling it.
> 1 votes

# Answer
Have you copied the .htaccess file? Sometimes, it is not copied, because files stating with an `.` are regarded invisible and non archive

Have you got

```
AddType x-mapp-php5 .php
AddHandler x-mapp-php5 .php

```

in your .htaccess?
> 0 votes

---
Tags: 6, migrations
---


# Question
Title: During checkout, when I click on review order, I would like to do some additional validation
When a user goes to checkout and clicks on "review", I would like to be able to hook into that process in order to do some custom validation.

How would I go about doing that?

# Answer
You can just do a custom validation handler on the checkout form. This would mean the validation is done *before* you get to the review order screen. Let me know if you need more details.
> 0 votes

# Answer
The Ubercart API provides a number of hook points for this. I would look at hook\_order as a starting point for something like this and perhaps check a few of the other API options for Ubercart.

In the past, I have used hook\_add\_to\_cart in order to review a product and determine if it should be allowed into the cart or not. Not that this is what you are trying to do, but the API provides for a lot of flexibility.
> 0 votes

---
Tags: 6, ubercart
---


# Question
Title: How to choose the default (or any) CKEditor toolbar?
OK, I'm obviously missing something. I've installed CKEditor into a D7 site, and all's well. The only problem is I can't figure out how to specify the toolbar that will come up by default in CKEditor-enabled fields. I've defined a new toolbar in .../ckeditor/ckeditor/ckeditor.config.js, but I haven't found any place in the site's config options (or the code, for that matter) that let me say that I want CKEditor to put up this particular toolbar. For that matter, I don't see any way to be able to choose the other toolbars in ckeditor.config.js (like DrupalAdvanced and DrupalFull). Any clarification out there? Thanks!

# Answer
I finally figured this out: See http://drupal.org/node/1434814#comment-5583354 for the solution. The most important bits are:

* If you're just using the basic CKEditor module, ckeditor.config.js is completely irrelevant to getting your toolbar set up. Ignore it.
* CKEditor toolbars are associated with text formats, like "Filtered HTML" or "Full HTML" (or, presumably, other text formats you might define). Each text format can be connected to exactly one toolbar; when a textbox with that text format appears, its toolbar will be presented.
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: Drupal multisite configuration with a single database and redirection based on IP
I need to implement multi site configuration in Drupal 7. I have a Drupal code base called example.com and two subdomains sub1.example.com and sub2.example.com in sites/ folder. I am using a shared database also. My requirement is to to redirect a user to sub1.example.com if the user enters the url http://example.com from country1. When any other user hits the same url http://example.com from country2 then he must be redirected to sub2.example.com. The user must be unaware of the country specific domain redirection.

I am using drupal 7.7. I installed ip2locale module for redirecting the users based on their IP and a domain access module also is installed.

> Is the domain access module really needed for meeting my requirement ?

If I have to use domain access module

> do I need to set up virtual host separately for each sub domain when domain access module is used? Is ip2locale module alone sufficient for redirection based on IP?

# Answer
> 1 votes
If you are using IP2Local and purely redirecting to completely independent url that has a directly associated database (users, content, configurations) you don't really need domain access. You could keep all the data in the same database (save time on table maintenance) and separate them with prefix's.

You will need domain access if you are centrally sharing content, users and admin tasks as well as the database but need to open or restrict access based on the domain that the user is accessing through. If your users need to cross from site1 to site2 or access common content, this would be the way to go. Domain gives you more flexibility and scalability that option 1 but may require a little more work to set up.

---
Tags: 7, redirection, multi-sites, domain-access
---


# Question
Title: Why isn't local.css file used in styling a page on a site?
I have been transferring a development site to a new computer and ran into a problem when I transferred the local.css file I had been using to style my content. While the file works fine on the old computer it is not working on the new even though the file configuration is identical.

The site is using a subtheme for Stark. Both theme are present and enabled. The general appearance of the site is now consistent with the Stark theme. I am using firebug to determine the css sources. If I select a superfish menu on my site, I get css input from system and superfish.css, but not from local.css. It is not being used at all because I can copy over a setting from superfish and change it in local without affect. My caches are constantly being flushed so that is not the problem.

Here is the directory structure:

* "example.div/themes/stark/stark.css" - used
* "example.div/sites/all/libraries/superfish/superfish.css" - used
* "example.div/sites/all/themes/sub\_stark/css/local.css" - not used.

The sub-stark info file reads:

```
       name=sub stark
       description = Stark
       sub-theme base theme = stark
       core = 7.x
       engine = phptemplate

       stylesheets[all][] = css/local.css

```

Configuration looks good. Caches are cleared. Have I forgotten a setting somewhere?

# Answer
> 1 votes
Well, I've got it to work by moving the file into the Sub-stark directory instead of a sub directory and changing the .info file. I am working on Windows 7 using an Oracle VM with Ubuntu, so there may be that is causing a problem.

---
Tags: theming
---


# Question
Title: Entire site broken because of one custom module! No pages found anymore. How to fix?
I wrote a custom module and implemented it. Now I cannot access any pages on my drupal site. They all say something like: Page not found. The requested page "/" could not be found.

I removed the module by hand from the table by running:

```
UPDATE system SET status=0 WHERE name='MyModule';

```

Even with this, no pages are working anymore. I thought it was an htaccess issue or a clean url issue, but even doing /?q=user does not get me to my login screen. Any ideas on how implementing my one custom module broke the entire website? My module was basically this:

```
function MyModule_menu() {
  $items['MyModule_views'] = array(
    'title' => 'MyModule test',
    'page callback' => 'MyModule_list',
    'access callback' => TRUE,
    'type' => 'MENU_CALLBACK',
  );
  return $items;
}

function MyModule_list() {
  return t('hello');
}

```

# Answer
I'm not sure why your menu item above took over all paths, it should have only responded to paths that start with '/MyModule\_view'. Maybe someone else can see what the problem is. However, I believe it's still causing problems because the menu registry hasn't been rebuilt. You'll need to clear that out to actually remove the menu item definition. Normally this would happen when you disable the module from 'admin/build/modules', but because you did this manually by altering the database that process didn't happen. If you use Drush (which I highly recommend) you can rebuild the menu registry with

```
drush cc menu

```

If you don't have Drush, then you can write a simple script to rebuild the menu even though you can't really access your site. The script is explained in an answer over on StackOverflow: https://stackoverflow.com/a/6912110/318158
> 5 votes

---
Tags: 7
---


# Question
Title: Custom error message + hide generic message
I'm working with the Brightcove Drupal module, and want to override generic error messages for users when an upload fails. I've added a custom error - but the generic message is still displaying before the custom message as follows:

* Notice: Undefined index: widget in brightcove\_field\_browser\_validate() (line 296 of /path/to/sites/all/modules/my\_module/my\_module/my\_module.module).
* This video is currently unavailable. Please note, it may take several minutes for large files to finish processing after being uploaded.

I can post code from the module if needed, but wasn't sure if this could be updated globally to always hide this type of message for users while still keeping custom 'user-friendly' messages.

Thanks!

# Answer
you can use the theme\_status\_messages function to do search and suppress certain messages.

The String Overrides module lets you do global text replacements which should work in your case.
> 1 votes

---
Tags: 7
---


# Question
Title: Page slide animation with horizontal anchor navigation
I want to realize a project with sliding pages (horizontally or vertically) similar to the one shown on www.viasko.de.

Is that possible with Drupal due to a different navigation concept via anchors, and not with urls? Does the URL dispatcher allow anchors?

# Answer
Drupal's menu system accepts paths like 'node/34#stuff' via the GUI, where 'node/34' is the internal path to a specific page (with the anchor). On the code level the url() function also allows to set an anchor via the 'fragment' option. So generally you shouldn't have problems with implementing anchor links in Drupal.
> 0 votes

# Answer
They used here element using html like map example

```
<a href="#speisekarte" title="">
    Speisekarte
</a>

```

Here the point to start the page

```
<a name="speisekarte" id="speisekarte"></a>
<div>Desc</div>

```

If you don't find a module you can make it custom
> 0 votes

---
Tags: theming
---


# Question
Title: How do I include a JavaScript library without using a module?
Note: I'm very new at using Drupal, so I may be missing something.

I've searched high and low, but I can't seem to find an answer to this.

I've got a custom Drupal theme based on Zen, and I want to include a jQuery plugin (specifically, Lightbox) into a page that needs it (I'm using Panels and Views to create custom landing pages). Frankly, I'd be happy even if I had to include it on the entire site.

I looked at JavaScript Libraries Manager, jQuery Plugins Module, but these didn't seem to be able to include CSS or images, which Lightbox requires.

I tried placed the script and CSS/image files in my theme's folder, and then using the following in `mytheme_preprocess_page()` in my theme's `template.php`:

```
$options = array('group' => JS_THEME);
drupal_add_js(drupal_get_path('theme', 'mytheme') . "/js/jquery.lightbox.js', $options);

```

This loads the JavaScript file OK, but it doesn't function correctly because it's looking for the images at the web root `/` (and I didn't include the CSS file, anyway).

I saw an example of using `hook_library()`, and this looks promising as it allows specification of CSS files as well, but I'm not sure where/how to include this setup code.

Also, I realize that there is a Lightbox module, but because the way that my content types and views are done, I can't add `rel="lightbox"` to the anchors...

# Answer
> 2 votes
It doesn't sound like you need to hook the theme system or deploy a module, why not try including the paths to Light Box's dependencies in one or more of your template files?

Better yet add the CSS and JS file paths (relative to the theme folder) to your theme's info file.

Stylesheets

Scripts

---
Tags: 7, javascript
---


# Question
Title: cannot get custom Omega stylesheets to load responsively
I have an HTML5 Omega 3 subtheme. I'm using the responsive grids, and Omega's (Alpha's) -wide -normal etc. css files are working.

But I can't get mine to. I have read the handbook and the wiki to no avail.

In mytheme/css I have

```
global.css
mytheme-alpha-default-normal.css
mytheme-alpha-default-wide.css

```

In my mytheme.info file I have

```
css[global.css][name] = my global stuff
css[global.css][description] = blah
css[global.css.less][options][weight] = 10

css[mytheme-alpha-default-normal.css][name] = my normal stuff
css[mytheme-alpha-default-normal.css][description] = blah
css[mytheme-alpha-default-normal.css][options][weight] = 10

css[mytheme-alpha-default-wide.css.less][name] = my wide stuff
css[mytheme-alpha-default-wide.css.less][description] = blah
css[mytheme-alpha-default-wide.css.less][options][weight] = 10

```

And I've enabled these in the Omega settings for the theme.

What happens is that all these stylesheets are loaded like the `global` one -- without any media query conditions at all, just like they were all global styles.

I've tried un-checking them. This just removes them. I've tried removing them from the .info file; this just removes them entirely too.

Can anyone help?

# Answer
> 4 votes
There's something odd about what you wrote in your question, because you mention `*.less` files. I'd expect to see just `.css`. Are they really `.less`?

But more importantly, you should not add `css[]` lines in the .info file for your width-specific css files. That makes them regular CSS files that will always be loaded. They will be listed in the list of CSS files, and can be turned on and off, as you see.

Take a look at the starter-theme .info file (e.g., `starterkit_omega_html5.info`), and you'll see that there are `css[]` lines there only for `global.css`, and not for any of the width-specific files.

Take those lines out. Omega will automatically generate loads for the width-specific files. It looks for the files based on the name pattern, and loads them with the appropriate media queries.

If the width-specific files do not appear at all in your page output with media queries, then there may be something wrong with your naming of the files. One common problem is that if your theme name has an underscore (e.g. "my\_theme"), then the filenames must have dashes ("my-theme").

One other oddity to know is that the width-specific files for all the widths narrower than the browser width are loaded. So, for instance, if your browser is at "normal" width, the global, narrow, and normal width CSS files will all be loaded, in that order.

MORE:

Don't forget to check the box "Enable the responsive grid" in the theme settings, and also check the box "Use this layout with the responsive grid" for each width you want to include

You should see something like this in every page that's output:

```
....
@import url("http://yoursite.com/sites/all/themes/mytheme/css/global.css?lxt4yy");</style>

<!--[if (lt IE 9)&(!IEMobile)]>
<style type="text/css" media="all">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-normal.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/normal/alpha-default-normal-12.css?lxt4yy");</style>
<![endif]-->

<!--[if gte IE 9]><!-->
<style type="text/css" media="all and (min-width: 740px) and (min-device-width: 740px), (max-device-width: 800px) and (min-width: 740px) and (orientation:landscape)">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-narrow.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/narrow/alpha-default-narrow-12.css?lxt4yy");</style>
<!--<![endif]-->

<!--[if gte IE 9]><!-->
<style type="text/css" media="all and (min-width: 980px) and (min-device-width: 980px), all and (max-device-width: 1024px) and (min-width: 1024px) and (orientation:landscape)">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-normal.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/normal/alpha-default-normal-12.css?lxt4yy");</style>

<!--<![endif]-->

<!--[if gte IE 9]><!-->
<style type="text/css" media="all and (min-width: 1220px)">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-wide.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-12.css?lxt4yy");</style>
<!--<![endif]-->

```

---
Tags: 7, theming
---


# Question
Title: How to log simpletest test results into files using drush test-run?
I would like to save simpletest test results into a log file. What bash commands should I use ?

I tried this command (example) but nothing is saved into /var/tmp folder :

```
sudo -u apache drush test-run Comment --xml /var/tmp

```

I use Linux , Drupal 7.12, Drush 4.5

# Answer
> 5 votes
I don't use drush test-run, but Drush options are always in the form `--xml=/var/tmp`.

c.f. http://drupal.org/node/1416198

From `drush help test-run`

```
 --xml      Output verbose test results to a
            specified directory using the JUnit
            test reporting format. Useful for
            integrating with Jenkins.

```

Try:

```
sudo -u apache drush test-run Comment --all --xml=/var/tmp

```

# Answer
> 1 votes
Try something like this:

```
sudo -u apache drush test-run > /var/tmp/whatever.txt

```

# Answer
> 0 votes
What worked for me finally was:

```
sudo -u apache drush test-run Comment --xml=/var/tmp >/var/tmp/test.log 2>/var/tmp/test.err

```

Thanks for help from hiphip and greg\_1\_anderson :)

---
Tags: 7, drush, testing
---


# Question
Title: How to make Drupal 6 contrib modules works in "wp-content/modules" instead of "sites/all/modules"
I want to make a new Drupal 6 installation, but I want to make contrib modules works in `wp-content/modules` instead of `sites/all/modules`.

Hacking may works, but I'm not so familiar with Drupal coding. I need to know best way and what file to hack.

# Answer
> 4 votes
The short answer is, you can't. Drupal scans recursively for modules in:

```
/modules                             Intended for Core's usage only.
/sites/all/modules                   Modules used by all your sites.
/sites/[site-name]/modules           Site specific modules.
/profiles/[current-profile]/modules  Current profile specific modules.

```

Sure you can hack core if you *really* want to force core to look somewhere else, though I must say I see little value in this, and strongly discourage it.

The relevant code is in /includes/module.inc and you can follow the current logic from module\_load\_all().

---
Tags: 6, installation
---


# Question
Title: Need a hook a little later then hook_node_insert
I am working on a module to unzip the contents of my file field after I have submitted the node. I originally tried to do this in hook\_node\_insert but this did not work for me because my file field has a custom file path and at the time of hook\_node\_insert the file is still in the default upload location and it is then moved to the custom file path at some later point.

I also though maybe I could implement my unzipping code hook\_file\_move (which gets called when the file is moved to the custom file path) but it seems that there is no way to verify that the node type from hook\_file\_move.

Is there some better hook to implement this unzipping code where I can both verify the type of the node and late enough in the content creation process that the file will have been moved to the location of the custom path.

# Answer
Did you try to make your module's weight higher, to make sure your hooks get executed after all other modules' ? The documentation states that node\_insert is called after file\_attach\_insert so it might be worth a try.
> 2 votes

---
Tags: hooks, files, nodes
---


# Question
Title: How to call up the argument passed to the View?
I have a view that reads the argument from panel url.

How can I call up the passed argument inside the "no result case" with html code?

Thanks!

# Answer
> 0 votes
I don't think it's possible with HTML, but 'No result case' allows you to use PHP, so arg(x) should work, x being the zero based position of your argument in the URL.

---
Tags: 7, views
---


# Question
Title: Can I use the first value of a multivalue field as another field? ("Cover" use case)
My content type uses an unlimited number of images as "screenshot". I would like to be able to manage the FIRST screenshot of the set as the "cover" of the content type, so to define a "field\_cover" and telling Drupal "The value for this field is the first value of field\_screenshot". In this way I could reference field\_cover in my views for some special cases (like showing the latest mynodes in home page, using the "cover" as the image).

# Answer
> 2 votes
I'm not aware of a "wrapper" field type, but you have a few options.

I've done the same myself in Views by filtering by the "delta" value, which is the individual values in a multivalue field. That way it's easy to require "delta = 0" and get the first value. This has a limitation of currently not working with arguments/contextual filters though.

A second option is the to ctools recently added support for delta values. You can render a field and set both offset, range and reversal of deltas.

Final option I can think of is Computed Field, which could be programmatically coded to act as field wrapper.

---
Tags: views, entities, media
---


# Question
Title: Views - Contextual filter -  "page not found"
I have a view that uses a contextual filters of type

> Content: Has taxonomy term ID (with depth)

The page display has the following path `/objects/%`
If I access the site through http://mysite.com/objects/all the view gets triggered and all my objects are listed, http://mysite.com/objects/silver also works fine (now only objects tagged with silver are listed), but if I use http://mysite.com/objects then I get a `"Page not found"` message, how can I solve this? I wan't the `/objects` and `/objects/all` to show exactly the same content.
Of course I could copy the display and add a path for `/objects` but that don't seem quite right.

# Answer
This is an unfortunate side effect of how the menu system works. When the paramter "%" isn't available, you match against a different path, and the View won't get called.

I suggest making /objects an alias to /objects/all, I believe this will then interact properly with the menu-system. If that's not the case, you can force the issue with Path redirect which will redirect the user with an HTTP-response code, and thus land the user at /objects/all.

I minor drawback of using Path redirect is that the redirect logically belongs together with the View, but is now configured somewhere completely different. For that reason, I would prefer to accomplish the redirect and View rendering with Page manager, which will allow you to group the HTTP-response and a Panel together in a more logical manner.
> 9 votes

# Answer
When you configure the contextual menu there are a set of options under *When the filter value is NOT in the URL*. Select *Provide a default value* and type `all`
> 0 votes

---
Tags: 7, views
---


# Question
Title: In which order should one build up a multilingual site?
I'm planning to convert (better rebuild) an existing site based on MediaWiki and a phpBB3 Forum to a shiny new Drupal based site. The MediaWiki is multilingual, though most content is in German.
My experience with Drupal is basic. I've done basic things with other CMSs and am familiar with PHP, MySQL and HTML.

A couple of weeks ago I set up a new Drupal 7.10 instance (locally).
My first try was migrating the existing MediaWiki content as articles into Drupal. I failed badly and could not find a way (on the web) realising this.
I ended up building the central and essential MediaWiki templates (which are very individually) as content templates. That worked pretty satisfying and I accepted to manually copy&paste the content in a later step (has somebody a monkey for me?).

Then I tried migrating the existing phpBB into a Drupal-based forum via a module (failed) and finally agreed on bridging those. The modules for this are actively developed and I let some more time pass as to get them more mature.

Beside those two central topics of the desired Drupal site, multilingual content is essential as well. For the wiki-like content even more than for the message board. In case of the wiki content, the users will be creators of new and translators of existing content.

While trying different ways and different modules for all the functionality, I have to admit, that I got hopelessly lost.
I'm not asking for a specific set of modules, I should use. I would have to define all functionality of the desired Drupal site and that's not the core of this question.

My question is rather: **In what order should I build up the site's functionality?**
That is, after having set and defined the access and user groups, should I first concentrate on the multilingual backend and translation pipeline (e.g. modules for multilingual content and translation)?
Or should I first get the templates for the wiki-based content right and implement the multilingual thing atop of that?
Both is somehow closely interconnected and -- as mentioned above -- I got lost while finding my own way.

*I hope, this question is not too broad and vague. If so, please let me know and I try even harder getting it more specific.*

# Answer
I would suggest starting with setting up the multilingual backend. Besides what Drupal core already offers you probably want to use the i18n module. Then you could move on to content migration. If there is no module that can do that for you I'd suggest writing a PHP script rather than manually copy/paste-ing (seeing as the amount of data seems to be fairly large). You could make use of either node\_save() or drupal\_form\_submit() for this task. The first option is a quicker way of adding nodes while the second mimics more closely normal node creation by invoking additional hooks. There's a solid amount of information about using them to create nodes programmatically available on the web that you can make use of. At what point to work on appearance (templates and theming) shouldn't matter too much, but it's probably somewhat easier at later stages when you already have the content to work with.
> 1 votes

---
Tags: 7, i18n-l10n
---


title: Clean URLs are broken in MAMP

text:
# Question
Title: Clean URLs are broken in MAMP
I'm using MAMP on os x 10.6.

Until this morning clean URLs where working on about 20 different D6 and D7 installations without problems.

All of a sudden clean URLs are broken on all installations. I'm not aware of having changed something in the MAMP or apache configuration.

Things I already checked:

* `phpinfo()` tells me that mod\_rewrite is loaded.
* I did not change any .htaccess files

Do you have any idea on where to look at?

Update: I think the .htaccess files are not loaded at all. I can write gibberish into the file and there are no error messages at all.

# Answer
The *.htaccess* files are ignored if the AllowOverride directive is set to *None*.
> 2 votes

---
Tags: uri
---


# Question
Title: Drupal fancybox views gallery - display only first item of attached images
I have multiple images attached to a node that act as a gallery using fancybox. In views I am attempting to only display the first attached image.

The idea is to only display the first image then when clicked, fancybox will go into gallery mode displaying all subsequent attached images.

I have tried the 'Group multiple values' showing '1value' starting from 0.

This works for only displaying the first item, but unfortunately when clicked fancy box does open but not in gallery mode. It just displays the first item.

What i need to do its open all attached images as a fancybox gallery but from only the first item.

Any help or ideas would be much appreciated.

# Answer
> -1 votes
Use the display CSS properties.

```
.field-content ul li{
    margin:0;padding:0;
    display:none;
}

.field-content ul li:first-child{
    display:block;
}

```

---
Tags: views, media
---


title: get node creation date in a view

text:
# Question
Title: get node creation date in a view
I'm trying to get a nodes "poll" created date and how much time it has until it closes in a view. but having a problem reaching that information for the available fields, I tried to create a relation with the content: author with no luck.

# Answer
Poll is a core module and it appears that it doesn't make the "end date" available to views. You could add your own "end date" field to the poll content type but then you have to enter it twice.

Or try the more advanced pollfield module:

```
Because pollfield allows you to build polls as part of the CCK system, this module provides a more flexible polling option than the Drupal core poll module.

```

Please let me know how it goes, I'm interested in the pollfield module myself, just don't have time right now to play with it ;-)
> 1 votes

---
Tags: views, polls
---


# Question
Title: Parsing the 'q' in drupal to get the current URL
So I am attempting to parse out the URL, so that I can get a specific page template to be used for a specific URL; if the URL is example.com/team, then use page-team.tpl.php.

However, when I do this, the URL I am getting (via $\_GET\['q'\]) always seems to be the URL from where I was, not the one where I am currently at. If I directly navigate to example.com/team/surf, it gives me "team/surf"; if I go to example.com/team it gives
"team/surf." If I refresh the page, it will then give me the desired one.

I dropped this code into my template.php file.

```
function theme_preprocess(&$vars, $hook) {
  switch ($hook) {
    case 'page':
      $normal_path = trim($_GET['q'], '/');
      $path_alias = drupal_get_path_alias($normal_path);
      $alias_parts = explode('/', $path_alias);

      if (($alias_parts[0] === 'team') && (count($alias_parts)) == 1) {
       $vars['template_file'] = 'page-team';
      }
      break;
    }

```

Do you have any idea on what is going on here?

# Answer
I'm not sure why your code happens to fail in some cases, and in some cases not. But what I would try is replacing that code with the provided by Drupal arg function.

On "team/surf", arg(0) will return "team", and arg(1) "surf". This is what I use myself, and hopefully that will solve the problem for you.
> 3 votes

# Answer
There is no need to parse the `$_GET['q']` yourself.
> 2 votes

---
Tags: theming
---


title: Two Columns with Display Suite?

text:
# Question
Title: Two Columns with Display Suite?
I want to override the default three-column layout used by the Display Suite module, and I want to use only the left and right columns, without the middle one.
What is the easier way to achieve this?

# Answer
> 2 votes
The easiest way would be to override the nd\_regions.css file in your theme and put something like the following in it:

```
.nd-region-header,
.nd-region-footer {
  clear: both;
}
.nd-region-left {
  width: 50%;
  float: left;
}
.nd-region-right {
  width: 50%;
  float: right;
}
.nd-region-middle-wrapper {
  display: none;
}

```

Simply don't put anything in the DS middle column, manage a gutter and you'll be fine.

# Answer
> 2 votes
I just now have a similar requirement. I want to be able to change the css file for a layout. But that would change the layout for all content that needs the original built-in layout.

In the end I think it easier to set up a custom layout. That will need a custom folder in your current theme. I just that for the first time and it works great.

So you could copy both the css and the tpl.php files from the display suite 3 col default files into your own custom folder at \sites\all\themes\yourtheme\ds\_layouts. In my case I now have a \sites\all\themes\bartik\ds\_layouts\rs\_2col\_stacked folder with these 3 files:

```
rs_2col_stacked.css, rs_2col_stacked.inc, rs_2col_stacked.tpl.php

```

It is easy enough to make it worthwhile because you can be total free to work with your custom settings and never sweat over messing up the built-ins. After I watched this video Display Suite for Drupal 7 - Part 2: configuring a layout on youtube I decided to get around to installing drush on my windows pc, then on a ubuntu server. The video is by a creator of display suite and near the end of it he shows how to very quickly create a simple custom layout. Then you can read over the short lines of code in the created files and adapt code to set up the custom layout your really need. You just need to copy default files and edit them as need. The .inc is a little tricky to understand but it's tiny. Let me know if you need more help.

---
Tags: theming
---


# Question
Title: How to theme help text of field groups in node form
I put some HTML tags in the help text of field groups in node form but HTML tags are automatically removed after saved the change. It seems that also there is no selection list of input format for help text. Is there any way to theme it?

# Answer
> 0 votes
Help text is run through content\_filter\_xss():

```
/**
 * Like filter_xss_admin(), but with a shorter list of allowed tags.
 *
 * Used for items entered by administrators, like field descriptions,
 * allowed values, where some (mainly inline) mark-up may be desired
 * (so check_plain() is not acceptable).
 */
function content_filter_xss($string) {
  return filter_xss($string, _content_filter_xss_allowed_tags());
}

/**
 * List of tags allowed by content_filter_xss().
 */
function _content_filter_xss_allowed_tags() {
  return array('a', 'b', 'big',  'code', 'del', 'em', 'i', 'ins',  'pre', 'q', 'small', 'span', 'strong', 'sub', 'sup', 'tt', 'ol', 'ul', 'li', 'p', 'br', 'img');
}

```

---
Tags: nodes, entities, 6
---


# Question
Title: How to create a simple list of links to Drupal panel pages?
I would like to create a simple HTML menu made of links to pages A, B, C created in Drupal (but not all pages, only a subset). Unfortunately, menu's in Drupal are displayed as `li` lists, not just a list of urls, which adds bullets to the display.

A view displayed as unformatted list would be great, but you cannot create a view of miscellaneous page links.

I could create a mini-panel and hardcode the links, but hardcoding is always a bad idea. Ideally, there should be a way to set relative links to pages and let Drupal generate absolute links.

What would be the best way to create a simple a list of links to pages created in Drupal? A block or a mini-panels are acceptable solutions.

# Answer
> 1 votes
Using an HTML list is semantically correct in this situation. If you literally want to create a list of links to pages in your site, why would you object to using semantically correct HTML via an intuitive element of site architecture (menus)?

Bullets are a superficial styling default for HTML lists and can easily be removed with CSS.

```
.block-menu-menu-name ul.menu li {
  list-style: none;
  list-style-image: none;
}

```

Using the Drupal menu system is still the easiest and most efficient way to create a list of links to pages within your site, even if you do not want to use an HTML list to display them.

You can easily override the theme functions that create any menu's HTML. In your theme's template.php file you can override theme\_menu\_link() and theme\_menu\_tree() for the menu you want to manipulate. Let's say the menu is called "Links List".

```
function THEMENAME_menu_link__links_list($variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<div' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</div>\n";
}

function THEMENAME_menu_tree__links_list($variables) {
  return '<div class="links-list">' . $variables['tree'] . '</div>';
}

```

Note that there are two underscores before the machine name of the menu in the function name.

This would result in a list of divs with links inside them. Also, you could omit the div wrappers and add a `<br />` after each link instead.

It seems like a lot of unnecessary work for what is essentially a superficial styling issue, but perhaps there some other aspect to your overall goal that would make this approach seem more appropriate?

# Answer
> 1 votes
You could create a View of miscellaneous page links, if the list of links was actually a list of a series of nodes with a particular taxonomy term applied to them.

For example:

Create a taxonomy vocabulary called "Page Links", and create a new taxonomy term for it called "Custom Menu One". Then, tag each of the pages which you want included in your list of links, with this Custom Menu term.

Now, you can go into the Views UI, and create a block View which outputs all nodes which have the taxonomy term "Custom Menu" applied to them. You can set up the view to use fields, and output the title of each node as a link back to the original content.

You'll also be able to configure the display settings for the View so that the links are output as a List, or Table, or unformatted, etc.

---
Tags: 7, uri, navigation
---


# Question
Title: Use background images without knowing programming?
I'm trying to set up a site using Drupal 7, and have very little knowledge of the stuff under the hood. If the answer is to edit some css, please give VERY simple instructions.

Is there a simple way to put background images in the Acquia Marina theme?

Or, are there similar looking themes that have this facility built in?

Thanks!

# Answer
You should change the body background selector in the css file of the template, for example

```
body{ background: url("path to image");}

```

More info how to use background css
> 2 votes

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


# Question
Title: How to alter the query that selects node in the admin/content page
i need to alter the list of nodes displayed in the admin/content page (the basic administrative page for content) depending of the role of the user. For example if the user has a role, i want him to display only pages with content type = article.

I thought i could modify the query using hook\_query\_alter

```
function provintegra_query_alter(QueryAlterableInterface $query){
    fb($query);
}

```

but i was wondering on how to add the condition i need and how to find the correct query to modify. Of course other solutions arre accepted, but i can't use views because i need to have a page that it's exactly like the one that is displayed normally (with the same filters and links for editing). I need to restrict visualization to certain content types (articles for example but also user defined content types) and if possible to content created by the user

# Answer
> 1 votes
Instead of doing custom SQL query alters, why not use a drop in replacement for the administration pages?

Views Bulk Operations (VBO) does just that, and ships with a replacement for the node administration page. And because VBO is based off views, altering them is trivial, and tasks like 'hide items of type article' become easy (and also critically, more maintainable going forward)

# Answer
> 2 votes
I had this issue in Drupal 6 just now, on the "/admin/content/node" overview page. I wanted to hide certain content types -- and you can't do that with views per se because the admin page is a form, where you can easily bulk update. Sorry that I'm not putting a D7 answer -- this may not be exactly what you are looking for, but it works for me in 6, and maybe others will find it helpful:

```
/**
 * hide child content types from /admin/content/node overview
 */
function [your module]_db_rewrite_sql($query, $primary_table, $primary_field, $args){
    if(arg(0)=='admin'&&arg(1)=='content'&&arg(2)=='node'){ // /admin/content/node page
        if($primary_table=='n' && $primary_field == 'nid'){
            if(!user_access("[your access callback for viewing this type]")){
                  $return['where'] = 'type != "[type to hide machine name]"'; // or you could use type == type_name
                  return $return;
            }
        }
    }
}

```

again.. that's D6, so I'm sorry but hopefully that will get you started

# Answer
> 2 votes
Best I can do. It works, but it's not pretty.

```
    function mymodule_query_alter(QueryAlterableInterface $query) {

      if (current_path() === 'admin/content') {

        // This bit avoids queries on the page that don't join the node table
        // Be careful if you have a node-related query in, say, a block on the page
        $tables = $query->getTables();
        $node_exists = FALSE;
        foreach ($tables as $alias => $table) {
          if ($table['table'] == 'node') {
            $node_exists = TRUE;
            break;
          }
        }

        if ($node_exists) {
          // add an access check around this next line
          $query->where($alias.'.type IN (:types)', array(':types' => 'article'));
        }
      }
    }

```

---
Tags: 7, theming, database
---


title: hook_menu_alter information

text:
# Question
Title: hook_menu_alter information
I am using drupal 6.22.

I have written a framework module that relies on submodules, when I install the submodule, I would like to update the administration menu to include some administration properties for the submodule.

This is the hook\_menu implementation on the framework and it works no problem:

```
function svm_mail_menu() {

$items['admin/settings/svm-mail'] = array(
  'title' => 'SeeViewMedia Mailing Framework',
  'description' => 'Framework Settings for the SeeViewMedia Mailing application',
  'page callback' => 'mail_settings', //this needs to direct to a tabbed page that holds the framework options such as general settings and account add/edit/delete
  //This page should also be a "welcome" page for the module listing where everything is found
  //'access arguments' => array('Administer SeeViewMedia Framework Settings'),
  'type' => MENU_NORMAL_ITEM,
);
$items['admin/settings/svm-mail/add-account'] = array(
'title' => 'Add Mailing Account',
'page callback' => 'add_mail_account',
'access callback' => TRUE,
'type' => MENU_LOCAL_TASK,
);
$items['admin/settings/svm-mail/view-accounts'] = array(
  'title' => 'View Mailing Accounts',
  'page callback' => 'view_mail_account',
  'access arguments' => array('Administer SeeViewMedia Framework Settings'),
  'type' => MENU_LOCAL_TASK,
);
return $items;
}

```

and this is the hook\_menu\_alter that I tried using, but it replaces my entire menu system

```
function ymlp_svm_mail_menu_alter(&$items) {
$items = svm_mail_menu();

$items['admin/settings/ymlp-svm-mail/update'] = array(
  'title' => 'Update YMLP Accounts Manually',
  'page callback' => 'ymlp_update',
  'access callback' => TRUE,
  'type' => MENU_LOCAL_TASK,
);
return $items;
}

```

How would I just add this little bit of menu to the original menu that I created without destroying everything else?

# Answer
If all you are doing is *adding* to an existing menu, there is no need to use a menu alter. Instead stick with plain old hook\_menu().

```
function ymlp_svm_mail_menu() {
  $items['admin/settings/ymlp-svm-mail/update'] = array(
    'title' => 'Update YMLP Accounts Manually',
    'page callback' => 'ymlp_update',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

```

Don't forget to flush the menu cache after the module is installed
> 3 votes

---
Tags: hooks
---


title: Sending two exposed filters fast

text:
# Question
Title: Sending two exposed filters fast
I'm using auto submit in exposed filter and if I changing the form control twice and fast(Before I'm getting answer on the first change) I will get wrong view list item. (So it seems to be that the first ajax request overrules the second selection) How can i fix it?

# Answer
The problem is that because of the auto-submit, you submit an ajax request as soon as the first filter is changed. It then doesn't matter that you make a second change, and the answer to the first request is already being processed.

The only solution that I'm aware of, is to not use the ajax functionality in Views, and instead implement your own, that for example waits one second after changing the first filter before submitting the form, allowing several filters to be changed in one request.
> 1 votes

---
Tags: views
---


# Question
Title: How to override the display of a field in a view: is preprocessing possible?
I want to override the display of a field in a particular view, so that rather than printing:

```
<div class="field-content">Content here</div>

```

I just want:

```
<p>Content here</p>

```

Is this something which is best done in a template (I assume):

```
views-view-field--view-name--field-tagline.tpl.php

```

Edit: I've solved this using the above template, and then removing the wrapping elements from the view in via the Views UI. If using preprocessing is more performant, I'd still be interested to know, so please drop a line below if so. Otherwise, this question is solved.

# Answer
I would suggest implementing the Semantic Views module. This allows you to easily customize the HTML that Views outputs for each level of elements (the entire view, row wrappers and field wrappers) from the UI. It is a bit easier to use and maintain than custom templates and preprocess functions.
> 2 votes

---
Tags: theming
---


title: Overriding views default templates

text:
# Question
Title: Overriding views default templates
I'm trying to override default views templates using \_theme\_process\_registry() function. It's ok, but i've got some trouble when administrator trying to redefine output via views\_ui interface. When he creates a new template, he obviously starts from default views templates (views/theme folder), so my templates is lost.

I'm trying to do so:

```
$theme_path = drupal_get_path('module', 'mymodule') . '/theme/default_templates';

/**
 * List all plugins trying to find overriden in our work directory
 */
foreach($plugins as $group_name => $plugins_group) {
    foreach ($plugins_group as $plugin_name => $plugin) {
        if (isset($plugin['theme']) && file_exists($theme_path . '/' .  strtr($plugin['theme'], '_', '-') . '.tpl.php')) {
            $plugins[$group_name][$plugin_name]['theme path'] = $theme_path;
        }
    }
}

```

but single field template doesn't work, coz its hardcoded in view\_plugin\_display.inc

```
// Field templates aren't registered the normal way...and they're always
// this one, anyhow.
$output .= '<pre>' . check_plain(file_get_contents(drupal_get_path('module', 'views') . '/theme/views-view-field.tpl.php')) . '</pre>';

```

Is anybody know how to fully override views templates to my own module directory?

And the second. I need to create more semantic markup like on dev.twitter.com.

How to redefine classes\_array to get rid of extra classes and div elements?

I'm using drupal 7 and views 3.

# Answer
Are the templates that are overriding your templates included in a Theme? Themes always take precedence over modules, so any template in a theme will always override the corresponding template from a module. You may want to consider re-phrasing your question to reference the original issue you are solving with your template files.

If you are referring specifically to Views output with your desire to create semantic markup, I would suggest the Semantic Views module.
> 0 votes

---
Tags: views, theming
---