# Question
Title: Is there a way to submit a form on an element's #ajax?
given a form like this:

```
function awesome_form() {

 $form['select'] = array(
     '#type' => 'select'
     '#options' => array(
        'hello' => t('Hello'),
        'good-bye' => t('Good Bye'),
     ),
     '#ajax' => array(
        'callback' => 'awesome_ajax',
        'progress' => FALSE,
     ),
 );

 $form['actions'] = array('#type' => 'actions');
 $form['actions']['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Save'),
 );

 return $form;

}

```

I want the ajax callback on the select box to fire a submission. So for instance, when someone selects "Hello" the form submits and when someone selects "Good Bye" the form submits. Right now (with the code above), awesome\_ajax() fires like it's supposed to, but I can't seem to get the form to submit (save the data in the database).

Also, I would like it if there wasn't a visible submit button on the page (as the submit button is unnecessary).

How would I do this?

thanks!

# Answer
You've not mentioned what your ajax callback is doing internal to it, but if all you want is to submit the form upon a change, you can do something like this in jQuery with no drupal involvement:

```
$('#edit-submit').hide();
$("#edit-field-FIELDNAME-0-value").live('change', function() {
  $('#edit-submit').click();
});

```

where `#edit-submit` is the id= in the form html of the submit input button and `#edit-field-FIELDNAME-0-value` is the id= of your select that you want the form submited upon change. Throw this and the appropriate drupal behavior wrapper into a js file and you can drupal\_add\_js() it from your form hook.

ADDITION:

I suppose `$('#form-id').submit();` is better than `$('#edit-submit').click();` above where `#form-id` is the id= of your form.

Also, if you are running D6, you'll need the jQuery Update module installed.
> 2 votes

# Answer
If there was no submit button there, I would normally make an ajax call when the selection field is changed, pass the data to a menu callback and had it's function do the saving to the database

```
$('select').change(function() {
  if ($(this).text() == 'selection 1') {
       $.ajax({
          type: 'POST',
          url: '?q=modulename/save_data',
          data: 'data=' + $(this).text(),
          success: function() {
             // do other stuff..
          }
       });
  }
});

```

For the menu callback on my custom module, it would be like

```
function modulename_menu() {
  $items = array();
  $items['modulename/save_data'] = array(
      'page callback' => 'modulename_save_data',
      'access arguments' => array('administer nodes'),
      'type' => MENU_CALLBACK
  );

  return $items; // make sure to clear your drupal cache in order for this menu callback to work
}

function modulename_save_data() {
    $data = $_POST['data'];
    // do the rest here...
}

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: can't upload files from computer in any wysiwyg editor
When I want to upload an image from an editor it only allows me to insert a URL and the ability to browse and upload a file is missing. So there's something that behind all the wysiwyg editor that is preventing me from doing this and honestly don't know where to start looking for this.

Tried FCKeditor, CKeditor, jwysywig and TinyMCE and in all those cases I can only insert a URL but not upload from hard drive

There's a tutorial I found on youtube here. At 0:19 you'll see 4 tabs called 'Image Info', 'Links', 'Upload' and 'Advanced' respectively. So my problem is the 'Upload' tab is missing from my editor as well as all other editor where this upload function is supposed to be.

# Answer
The IMCE project provides upload capabilities to a variety of WYSIWYG editors. Check the project page for the appropriate way to install it for your particular editor.
> 4 votes

# Answer
If you are using D7 and need simple image upload from computer, CKEditor and One Click Upload will be another solution. No need IMCE in this case.
> 0 votes

---
Tags: 6, wysiwyg
---


# Question
Title: How do I set cron using performance page?
I am not able to set up the performance setting for cron duration, and automatic cache clearing setting in admin performance page.

I am not able to find the exact issue. I am clearing the cache manually everyday currently.

Can anyone provide better solution for this?

I changed the settings, and clicked on the save button of the form,but settings are not saved. This happen with both cron and cache duration settings.

# Answer
Please go to Cron Settings (*http://example.com/drupal7/admin/config/system/cron*) to set it, default is 3 hours.
> 1 votes

---
Tags: 7, performance
---


# Question
Title: call mp3player field (CCK Field) in a page
I Use MP3 Player module to play audio files. I'm looking for a PHP code to call MP3 Player from a specific node. (e.g. node 4) how can I do that ?

this code doesn't work:

```
<?php
$node = node_load(4);
print $node->field_audio[0];
?>

```

this is the result of `print_r($node)` in node 4.

```
stdClass Object (
[nid] => 4
[type] => story
[language] => en
[uid] => 1
[status] => 1
[created] => 1343931282
[changed] => 1343931282
[comment] => 2
[promote] => 1
[moderate] => 0
[sticky] => 0
[tnid] => 0
[translate] => 0
[vid] => 4
[revision_uid] => 1
[title] => 5455
[body] =>
[teaser] =>
[log] =>
[revision_timestamp] => 1343931282
[format] => 1
[name] => admin
[picture] =>
[data] => a:0:{}

[field_audio] => Array (
[0] => Array (
[fid] => 7
[uid] => 1
[filename] => audio.mp3
[filepath] => sites/default/files/audio.mp3
[filemime] => audio/mpeg
[filesize] => 3663455 [status] => 1
[timestamp] => 1343931251
[list] => 1
[data] =>
)
)

[last_comment_timestamp] => 1343931282
[last_comment_name] =>
[comment_count] => 0
[taxonomy] => Array ( )
)

```

# Answer
> 1 votes
From the readme.txt file of that module.

> Pop this code anywhere to insert an audio player:

```
if (module_exists('mp3player')) {
  print theme('mp3player', 'Default', $audio_file_url, $audio_title, $audio_artist, $description);
}

```

---
Tags: theming, 6, entities
---


title: Show subterms in a page

text:
# Question
Title: Show subterms in a page
I have two categories and each one has subcategories. I put the parent categories in a menu. What I need is: when I click a parent category its subcategories should be shown in a new page.

How I should that? I'm using Drupal 7.

# Answer
> 0 votes
Taxonomy VTN provide new pages for taxonomy terms, as described in its page it provide what you want by `Terms of a parent: taxonomy_vtn/voc/xxx/xxx` option

in Drupal 7 you can use views to show child terms in page when you click on parent term:

1. create new views for `taxonomy terms` (you should select `taxonomy terms` in creation form)
2. create page display
3. select `taxonomy/term/%` as path
4. use `argument`

# Answer
> 0 votes
In drupal 7 you don't have arguments, but you have Contextual filters and Relationships. I have managed to use those to get parent term but not child terms.

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


title: Editor Persons Who Copy/Paste From Word

text:
# Question
Title: Editor Persons Who Copy/Paste From Word
We have many editors that are going to submit documents for appearance on our website. Most documents come in the form of a .doc etc. What would be the best method of importing the text into a content node?

# Answer
> 4 votes
WYSIWYG \+ CKeditor provides a "Paste from word" option; it doesn't do any automated importing, but does provide a popup window containing a textarea for the user to paste from word. The pasted content is then cleaned up and converted to HTML, and finally placed in the WYSIWYG as normal content.

# Answer
> 0 votes
I've just tried CKeditor it's a stand alone module, it does not depend on WYSIWYG. Download it and install it, then go to CKeditor website and download the library. I had troubles with the CKeditor for drupal in the CKeditor website, so i suggest you do download just the CKeditor (the first one), then extract the content of ckeditor folder into modules/ckeditor/ckeditor.

This module provides you a lot of functionalities such as 'force paste as plain text', 'check spelling on typing' and others. I found it more complete than WYSIWYG module with different libraries such as Tinymce, FCKeditor and CKeditor.

---
Tags: nodes, 6
---


# Question
Title: How to:Pass arguments to views and use that as contextual filter-in code
I have a views created in code. I am passing arguments(for contextual filters) to this view from another view like this:

sitename/apage?ids=1,2

Q1. Is this the correct method? If not what is?

Q2. How do i retrieve 1 and 2 (above) in the view where i want to use them as filters(contextual) for products/nodes with these ids.

Please help!

# Answer
> 0 votes
Contextual filters are passed not like $\_GET parameters but like part of an url (by $\_GET parameters exposed filters are sent). if you want send several values for one contextual filter - you need to separate them with comma or plus.

For example you have view with url '/product' and 2 contextual filters - 1st filter is product ids, and second one is country id. The url of a view can look like this 'product/12,45/55' In this example view will take 12 and 45 as product id and 55 as country id.

---
Tags: views
---


title: How to install a patch to drupal 7

text:
# Question
Title: How to install a patch to drupal 7
I recently exprience one problem that requires a patch. I downloaded that file .patch, but have no idea how properly to install that to my hosted website.

# Answer
> 6 votes
If you can shell into the account, you

```
cd /var/www/somewhere/docroot/sites/all/module
patch -p1 < /path/to/the/patchfile

```

Depending on how the patch was rolled, you may need to adjust the number after the -p to get it to apply properly. The man page can give you more details.

If you can't shell into the host, then you need to downloads the files(s), apply the patch locally and then upload them. This question give guidance, or you can cut to the chase and check out TortoiseMerge.

---
Tags: version-control
---


# Question
Title: newly created fields values are not loaded with node_load
I am loading nodes with node\_load in one of my tpl.php, so i can get custom built teasers of nodes of specific content type in that tpl. Everything works fine, but from some unknown point of time i am not able to pull field values with node\_load. Fields are included in node object, but there are no values in array!

For other custom fields i am able to get values, but for every newly created field- no value! (value is present in edit form and in database)

I am node\_load-ing from tpl file of another content type. When i am trying to load those new fields from the tpl.php of its own content type, they are appearing.

But i see no logic because i have other custom fields that are being read with no problem.

Help please, i am pulling my hairs!

# Answer
Oops.

All my values are there. I was fooled by output, reading values from wrong nodes. I have complex loops here pulling out nodes so i was fooled.

How trivial :(
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Lost access to permissions checkboxes at admin/config/group/permissions/node/<group>
Not sure what happened. I'm using Drupal 7.15 and the latest OG dev version (2.x) and for some reason, I lost access to all permissions checkboxes at admin/config/group/permissions/node/ - It's not even showing them in read-only mode, they are just not there.

I do have OG access control and field access modules enabled and I haven't done much but trying to create a new group and new content.

Rebuilding permissions or uninstalling the modules completely didn't help.

Any idea?

# Answer
I think I found a corresponding bug: http://drupal.org/node/1649186
> 0 votes

---
Tags: organic-groups
---


# Question
Title: How can I insert search box in front html page?
I tried to show the search box in a custom front page, which is a regular HTML page.

How can I achieve it?

# Answer
I'm not sure if this is exactly what you're asking, but if you want to output a block directly in code you can use module\_invoke().

IE.

Drupal 7

```
$block = module_invoke('block', 'block_view', 'current_search');

```

Drupal 6

```
$block = module_invoke('block', 'block', 'view', 'current_search');

```

Then render the contents of $block.
> 2 votes

---
Tags: javascript, search
---


# Question
Title: remove Anonymous user from "Entity Reference" users list
in my case a project has a technical team, so project content type has a user reference field which is created by Entity reference module. but in node creation form, an "Anonymous" user is available to select.

how can I remove it?

# Answer
One way would be to create a View with an "entity reference" display to show all users with an id greater than zero, then use the Views "Entity selection mode" for your entity reference field:

You can choose the View you just created and the anonymous user will no longer show.

There's also the Entity Reference View Widget module which provides an advanced version of this functionality, though it's still in alpha.
> 6 votes

---
Tags: 7, entities
---


# Question
Title: How to get the node id before saving the node in drupal 6?
I have created a content type called 'inquiry.' I am using the rules module to send an email after submitting an inquiry. My requirement is to get the node id before it is saved. I need to generate a link from that node id so the inquiry handler can view the inquiry by clicking on that link.

# Answer
You can use hook\_nodeapi presave option to get node content before saving the node.

**Example :**

```
function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      print $node->nid;
      exit;
    break;
  }
}

```
> 1 votes

---
Tags: 6, nodes, hooks
---


title: Alter field settings using hook?

text:
# Question
Title: Alter field settings using hook?
**EDIT:** I need to alter the settings of an entity reference field for administrators only. I need to change from the settings in the first image, to the settings in the second image.

The reasoning is that normally when creating content, I want users to select from the options available in the view. The options in the view are the "Bands" (a content type) that each individual user has created. However, if an admin needs to moderate the content, they are not allowed to save it after editing because the content of the field is not an option available to the admin (i.e. the band entered by the original user, and currently saved to the entity reference field, is not a band created by the admin and is therefore not an option in the admin's array). On save by an admin, it fails to save and throws an error of "The referenced entity (node: XXX) is invalid", staying on the edit page.

I tried changing $form\_state through hook\_form\_alter, but apparently $form\_state settings aren't saved on submission. So, I tried adding the alters to a validation function, which also didn't work for me. Then, I found the settings within $context of hook\_field\_widget\_properties\_alter, but it seems that $context can only be referenced and not altered. I also came across this post, which seems to state that there isn't really a hook for altering field settings.

Unfortunately, I have realized that I really need this feature in order to moderate my site. As always, any help is incredibly appreciated, as this issue seems to be beyond my abilities.

**Here's some screenshots as requested by Minty:**

Casual user's options, populated by the view, include only their own bands

What I want in the admin's options, which should be all the bands authored by all users. (note that it currently shows all bands, because I figured out how to do contextual filter in the view based on the current user, not because I was able to alter the field settings as asked by the issue):

Without the above fix, only the admin's bands appear in the list when editing a node. Therefore, as stated in the issue, it throws an error that the previously saved band is not a valid option for the field, and the node cannot be saved.

# Answer
> 3 votes
With respect to your original post, I ran into this exact issue here in drupalsixlandia and resolved it with a dull ax inside of views. By exact meaning I wanted to have a select list of bands created by a user presented to them when they wanted to add an album, but when an admin went in to add/edit things, s/he should see all of the bands on the system.

So, I created a view and used this view to populate the band Node Reference field in the album type in CCK.

I called it `my_band` and it filters on published bands and returns the Node Title of the band as the field. It has one argument, or in D7 a contextual filter, User Uid and in `action to take if argument not present` I provide a default argument via PHP code:

```
global $user;

if (in_array('super user', array_values($user->roles))) {
  return -1;
} else {
  return $user->uid;
}

```

Then in the Validation of that argument, I again use PHP:

```
if ($argument == -1) {
  return FALSE;
} else {
  return TRUE;
}

```

with display all values if validation fails.

So, now what happens (here at least) is if a casual user wants to create an album, s/he is presented with a list of only the bands s/he has created. But, if any user with the `super user` role wants to create or edit an album, the validation is forced to fail, and the argument is ignored and all bands in the system are returned.

Perhaps with some D7ing of the code above this might work for you.

# Answer
> 0 votes
The `$form_state` variable will be processed when the form is validated, when the user-submitted values are inserted into the array. So any changes you add when the form is first being built won't be reflected once it's been validated/submitted.

The most common method I've seen to manipulate the `$form_state` is in a custom validation function, it might be worth giving that a try:

```
function entityreference_widget_form_alter(&$form, &$form_state, $form_id) {
  if($form_id ==  'review_node_form') {
    $form['#validate'][] = 'entityreference_widget_form_validate';
  }
}

function entityreference_widget_form_validate($form, &$form_state) {
  $form_state['field']['field_review_band']['und']['field']['settings']['handler'] = 'base';
  // etc...
}

```

# Answer
> 0 votes
From what I can tell, the problem seems to be that you're filtering the view for bands authored by the current user. Then, when the admin tries to submit an edit form with a band that s/he is not the author of, the form gives an error.

If this is accurate, maybe the best solution is not to manipulate this in the form but in the view. You could change the view logic to show a band if the current user is the author OR if the user is an admin. I'm pretty certain you can achieve this with the Views Or module. Your two criteria (author, admin) would need to both be checkable with a filter or both with an argument (you can't do 'argument OR filter'), but I think this is the case. I would then disable (`'#disabled' => TRUE`) the form element using a `form_alter` when an admin is viewing it, so that they can't set it to any band.

If not, another option is to use a Views hook to remove the author filter if the current user is an admin. This would achieve the same effect described above.

One thing to consider: which widget are you using for the band select? If it's anything other than autocomplete, this method may not be advisable because it would mean loading all the bands on the page as `<select>` options or whatever. If this a *very large* number of bands, it could seriously slow down your page.

---
Tags: entities, hooks
---


title: Field Type list in module creation

text:
# Question
Title: Field Type list in module creation
I'm trying to adapt the next code from the book: http://www.amazon.es/Drupal-Development-Experts-Voice-Source/dp/1430228385/ref=sr\_1\_1?ie=UTF8&qid=1327316185&sr=8-1

```
function _job_post_installed_fields() {
  $t = get_t();
  return array(
    'job_post_company' => array(
      'field_name'  => 'job_post_company',
      'label'       => $t('Company posting the job listing'),
      'type'        => 'text',
), );
}
/**
 * Return a structured array defining the field instances associated with this content type.
*/
function _job_post_installed_instances() {
  $t = get_t();
  return array(
    'job_post_company' => array(
      'field_name'  => 'job_post_company',
'type'
'label'
'widget'
'type' ),
  => 'text',
  => $t('Company posting the job listing'),
  => array(
=> 'text_textfield',
      'display' => array(
        'example_node_list' => array(
          'label'       => $t('Company posting the job listing'),
          'type' => 'text',
        ),
), ),
); }

```

But I can find anywhere a list of types I kind use instead of "text".

My question is: Can you help me find a place where I can find a list of possible images? How that code would be if I wanted to create an image field, or a tag list field?

Thanks

# Answer
For field definitions, I find that the easiest thing to do, is to create the field in the UI and fetch the definition using `field_info_field` and `field_info_instance` and then dump the variable using the devel module (`dpm`) oe something similar.

Alternatively you could browse code, field types are defined in `hook_field_info` and widgets are defined in `hook_field_widget_info` (the form for the field) and formatters are defined in `hook_field_formatter_info` (how fields are rendered).
> 2 votes

# Answer
I do what googletorp mentions often as well.

I dont remember a drupal.org page that lists the field types possible, but there are many blog posts that talk about this topic, for example from http://ado.io/blog/drupal-7/working-programmatically-with-fields-in-drupal-7

A brief list from that blog post gives us:

```
Field types
Field types out-of-the-box are listed below, machine name of the field type is the highlighted one. You’ll need this later when it’s time to programmatically create one.

BOOLEAN :: list_boolean
DECIMAL :: number_decimal
FILE :: file
FLOAT :: number_float
IMAGE :: image
INTEGER :: number_integer
LIST (FLOAT) :: list_float
LIST (INTEGER) :: list_integer
LIST (TEXT) :: list_text
LONG TEXT :: text_long
LONG TEXT AND SUMMARY :: text_with_summary
TERM REFERENCE :: taxonomy_term_reference
TEXT :: text

```
> 0 votes

---
Tags: nodes
---


title: PHP not being eval'd on a node

text:
# Question
Title: PHP not being eval'd on a node
I created a content type called informational, that has only one field in it, the default body textarea, I added into it `<?php echo 'test';?>`, and chose the PHP Filter option, in my page--informational.tpl.php all I'm doing is printing that field, and it's printing it as 'plain text' format. I checked in the DB and it's saved as PHP code.

P.S. I'm an administrator of the site, and I have all permissions.

# Answer
> 0 votes
If you use print render($content); and your code is displayed as it is on an Informational page ("echo 'test';") you should check PHP code configuration page (?q=admin/config/content/formats/php\_code). Here you set the roles who can use this text filter (by default is the 'administrator') and you enable or disable PHP code evaluator. Ensure that 'PHP evaluator' checkbox is on. I hope this will help you.

---
Tags: 7, nodes
---


# Question
Title: is there a way to change multiple tags at once?
I decided to change a tag which is commonly used. Is there an easy way to change it for all my content or do I have to manually go in and change each one? Thank you.

# Answer
> 1 votes
If you changed the tag itself from taxonomy. It will change for all content that use the tag. The only issue you may run into is if your doing url paths based on any taxonomy terms.

---
Tags: taxonomy-terms
---


# Question
Title: Custom content for several Spanish speaking countries
I am on Drupal 7.

I need a website that will have different versions for each country in Latin America, where many countries speak Spanish. I was considering using one language per country, but as far as I am concerned, Drupal has only one Spanish version. At least, it doesn\`t have one Spanish for Costa Rica, another to Honduras, Panama, El Salvador, Colombia and so forth. So I was considering creating one flavor of Spanish per country in Drupal (I would create new custom languages like "es-country code") and loading all the Spanish vocabulary again and again into these alternative custom languages. Do you think this approach works? I would like to take advantage from the fact that when using localization (i18n) you can set one single structure/navigation for the website accross the languages. The content across different countries will usually be the same, but sometimes it will be different. Working with i18n I can duplicate content accross the countries and change the small details wherever I need.

So my question isn\`t technical, but broader. Do you think this approach is good? Which strategy/approach would you use if you needed to content customization per country where some of these countries speak the same language? Thank you

# Answer
I think it's the best solution, or at least we used the same. In Switzerland, we have the Swiss German, that is a little bit different from German.

So we took the German translation as a base and created another language, like de-ch. Then with i18n and all other modules, we translated the differences.
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: Include HTML in theme_pager_next $text variable?
Is it possible to include markup in the $text variable of theme\_pager\_next()? I find that whatever I set the variable to gets output as a string, rather than being rendered as HTML. Here's some example code as would be found in template.php:

```
    function theme_pager_next($variables){
      $text = '<span>test value</span>';

      /* Remainder of function call goes here ...*/

      return $output;
    }

```

I would like be able to add an image to the pager text. I realize I could also use CSS background images, but would prefer to print markup to the page if at all possible.

Is there something I'm overlooking?

# Answer
> 1 votes
If the rest of the code is the same used in theme\_pager\_next(), then it is not possible to add HTML tags to `$text`.

This is because `theme_pager_next()`, and theme\_pager\_last() call theme\_pager\_link(). `theme_pager_next()`'s code is the following one.

```
if ($page_new[$element] == ($pager_total[$element] - 1)) {
  $output = theme('pager_last', array('text' => $text, 'element' => $element, 'parameters' => $parameters));
}
// The next page is not the last page.
else {
  $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters));
}

```

`theme_pager_link()` then contains the following code.

```
$attributes['href'] = url($_GET['q'], array('query' => $query));
return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';

```

As it calls `check_plain()`, if `$text` contains HTML tags, they are shown as plain text.

To achieve what you are trying to do, you should override `theme_pager_link()` with a theme function that doesn't call `check_plain()`. filter\_xss() could be a better function to use in this case, but remember to pass in `$allowed_tags` the list of the tags you want to allow.

As side note, when you want to alter the content of the `$variables` array a theme function gets, in Drupal 7 you can use its preprocess functions. Every theme function has preprocess functions, and in your theme that is `THEME_preprocess_pager_next()`. (Replace THEME with the short name of your theme.)

---
Tags: 7, theming, paging
---


# Question
Title: Retrieve data from Field API programmatically
I have a custom field called phone\_number for the user. I need to retrieve the data in it from the database and use it to call other functions. I've looked through the Field API and I can't find the specific function. I read somewhere in the Field Attach API that most of the functions there take $entity as a variable but none of the functions there gives me what I need. Please help.

# Answer
> 1 votes
There are two solutions: use Entity API (http://drupal.org/project/entity) and create an object wrapper around the entity and just $phone = $wrapper-\>phone\_field.

Or use the field\_extract module (http://drupal.org/project/1158878) which provides two functions for extracting data from Field API fields.

Or third, code it yourself, but you don't want to do that.

(I wrote the field\_extract module so I am biased.)

# Answer
> 2 votes
Use Field data extraction API module to accomplish your job of field data extraction.

As per the documentation, you have to write this in yourmodule

```
  $phonenumbers = field_extract_values('node', $node, 'phone_number');

  $result = someCustomFunction($phonenumbers);

  function someCustomFunction($user_phonenumbers){

   // Do something here and return value

   }

```

# Answer
> 0 votes
The entities already loads a field data. if you have attached some fields to user you can use this as $user-\>myfield but sometimes in my practice field data has not appered. In that case you can load a entity load functions like node\_load() or user\_load()

---
Tags: 7, entities
---


title: Drupal install in sub folder

text:
# Question
Title: Drupal install in sub folder
I am trying to install a drupal site that I built a while back. I put it in a sub folder for viewing purposes and am having trouble logging in. I got the site installed, the DB connected but when I go to myurl.com/sitename/user I get a 404 error. The site is in maintenance mode so I can't get into the backend system. I know the site is partially working as when I go to myurl.com/sitename I get the maintenance page with all broken links. I did some searching and made sure my .htacces file was updated with this code:

```
RewriteBase /sitename
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

But still not working... What else should I be doing here? THanks

# Answer
Make sure to configure your base url in your settings.php file and revert your .htaccess to the default from drupal.
> 2 votes

---
Tags: .htaccess
---


# Question
Title: How to validate a form without the user pressing submit?
Right now I am working on a custom module where I have a 'view' page for viewing fields from my custom table in my database. The page basically just lists the field labels and values. I plan to have a feature to email the information on the page when the user clicks on a link/button, but only after certain fields are valid. Now if the fields aren't valid, I want to redirect to an 'edit' form page so that the user can edit certain fields. I also want to apply the form validate functions at the same time, so that inputs the user has to fix would already by highlighted in red.

However after looking at the form api and form quickstart guides, it seems to me that the only way to do that is to have the user click a submit button. Is there anyway to apply a validation function to the form right after it is loaded?

# Answer
> 3 votes
Clientside Validation will do your job.

You may however have to modify a javascript a little bit by incorporating `jQuery('input').blur(function(){ //invoke the clientside validation });`

---
Tags: 7, forms
---


# Question
Title: problem in admin_path module with my custom content type paths
I have created a content type "Test".

The content which I created of type "Test" have the paths like this "test/content1, test/content2 etc. means test/\*".

So I entered the path "test/\*" in the administrative pages.

But when I try to open any content of type "Test", First the url becomes like this "#overlay=test/content1" and then it redirects to "test/content1" and does not appear in overlay.

I tried some other paths of the contents of some other types and they are working fine in overlay.

So what is the problem with my custom content type? Any one who have some idea about t his?

# Answer
> 0 votes
Check out overlay\_paths module. Should solve your problem. Sounds like admin\_paths() isn't accepting up your url aliases. http://drupal.org/project/issues/overlay\_paths.

---
Tags: 7, nodes, modal-dialogs
---


# Question
Title: How do I create an ideogram-based 'features' list on nodes?
I'd like to create a simple checklist-style list on a node. How can I do this?

I presume CCK is involved. I'm thinking that it would follow some logic like this: the node editor checks applicable boxes for the relevant feaures. If a box is ticked, then an image is displayed in the list (and so on) on the node.

# Answer
> 1 votes
If you get a Drupal 6 specific answer, that's great, but in the meantime, I would suggest you look at this question. It involves Drupal 7, but the basic principal is the same. If I have had the experience of doing this in D6 I would have added the information to that question, but I have not.

# Answer
> 1 votes
If you know a little PHP you can do this with Custom Formatters and/or Display Suite and/or Views PHP. Create the checklist with CCK, then when you render your image, load the node and see if the relevant checkbox is ticked. If it isn't just render an empty string.

http://drupal.org/project/custom\_formatters

http://drupal.org/project/ds

http://drupal.org/project/views\_php

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


# Question
Title: Can entities as users exist without being tied to nodes
Can entities as users exist without being tied to nodes, I'm starting a site that I don't want a lot of overhead and it will have a lot of users and they will be contacting each other often.

# Answer
In D7 Users are an Entity type, they are their own Entity type. A Node is another entity type with various bundles such as Page, Article, etc.

Taxonomy is another example of an Entity.

An Entity does not necessarily mean a "Node" in drupal 7.

See this introduction to Drupal 7 Entities on drupal.org
> 1 votes

---
Tags: users, entities
---


# Question
Title: Using hook_views_pre_execute in my module, why does my new query give a strange result?
I have a view which I could not get to function the way I wanted through the Views interface, so I implemented hook\_views\_pre\_execute in my module (following the steps in http://drupal.org/node/409808).

My rewritten query (see below) adds a conditional with a subquery to the WHERE clause of the original query. I've tested it in phpMyAdmin, and it works perfectly. But, when testing the View in the Drupal, it acts like the NOT IN conditional does not exist. (ie. I get 3 results instead of 2).

One thing I found while searching for answers was someone saying that `db_rewrite_sql` (which is a function called by Views when it executes the query) is unable to handle "complex queries". Could this be my problem?

Does anyone have any idea why this is behaving strangely?

Here's the hook\_views\_pre\_execute code in my module, with the modified query.

```
function vmr_test_views_pre_execute(&$view) {

  if ($view->name == 'collected_machines_by_site' && $view->current_display == 'panel_pane_2') {
    $site_id = $view->args[0];
    $date = $view->args[1];
    $query = "SELECT node.nid AS nid, node.title AS node_title
FROM node node
LEFT JOIN content_type_machine_financials node_data_field_machine_reference_url ON node.vid = node_data_field_machine_reference_url.vid
INNER JOIN node node_node_data_field_machine_reference_url ON node_data_field_machine_reference_url.field_machine_reference_url_nid = node_node_data_field_machine_reference_url.nid
LEFT JOIN content_type_machine node_node_data_field_machine_reference_url_node_data_field_current_location ON node_node_data_field_machine_reference_url.vid = node_node_data_field_machine_reference_url_node_data_field_current_location.vid
INNER JOIN node node_node_data_field_current_location ON node_node_data_field_machine_reference_url_node_data_field_current_location.field_current_location_nid = node_node_data_field_current_location.nid
LEFT JOIN content_type_site node_node_data_field_current_location_node_data_field_location_id ON node_node_data_field_current_location.vid = node_node_data_field_current_location_node_data_field_location_id.vid
WHERE (node.type in ('machine_financials')) AND (node_node_data_field_current_location_node_data_field_location_id.field_location_id_value = '" . $site_id . "' )
AND node.nid NOT IN (SELECT DISTINCT node_data_field_mach_ref_url.field_mach_ref_url_nid AS rev_event_nid FROM node node LEFT JOIN content_type_revenue_event node_data_field_mach_ref_url ON node.vid = node_data_field_mach_ref_url.vid WHERE (node.type in ('revenue_event')) AND ((DATE_FORMAT(field_transaction_date_value, '%Y-%m-%d') <= '" . $date . "' AND DATE_FORMAT(field_transaction_date_value, '%Y-%m-%d') >= '" . $date . "')))";
    $view->build_info['query'] = $query;
    dpm($view);
  }
}

```

EDIT: I've been troubleshooting, and came across something that is just way too puzzling. I used the following code to see if my subquery was working in Drupal.

```
$subquery = "SELECT DISTINCT node_data_field_mach_ref_url.field_mach_ref_url_nid AS rev_event_nid FROM node node LEFT JOIN content_type_revenue_event node_data_field_mach_ref_url ON node.vid = node_data_field_mach_ref_url.vid WHERE (node.type in ('revenue_event')) AND ((DATE_FORMAT(field_transaction_date_value, '%Y-%m-%d') <= '" . $date . "' AND DATE_FORMAT(field_transaction_date_value, '%Y-%m-%d') >= '" . $date . "'));";
    $result = db_query($subquery);
    for ($i = 0; $i<3; $i++) {
      dpm(db_fetch_array($result));
    }

```

And I'm getting NOTHING. I used a `dpm()` statement to print the subquery with the dates already substituted, as seen by the program, then copy-pasted that into phpMyAdmin and it worked PERFECTLY! So somewhere along the line, whatever Drupal is doing is causing the above subquery to just not work. Any ideas at all would be helpful at this point. I'm thinking about bypassing Drupal's database abstraction entirely just so I can get the real results for this subquery.

EDIT 2: I solved the problem by just using mysql php functions directly, instead of going through Drupal's db\_\* functions. I'm going to leave this open in case anyone can explain why the subquery was returning nothing when using Drupal's database abstraction functions.

# Answer
In the dull axe arena, it looks to me that db\_rewrite\_sql() does it's "magic" by looking for WHERE, so, try changing WHERE to where, mysql shouldn't care, and this MIGHT bypass the re-writing and allow your code to run as is. Of course, this defeats drupal's permissions checking.
> 2 votes

# Answer
You need to set pager query as well:

```
$view->build_info['count_query'] = $query->countQuery();

```
> 0 votes

---
Tags: views, database
---


# Question
Title: field template for a specific content type
I've read from http://drupal.org/node/1089656 that I can create a template for a field in specific content type as **field--field-name--content-type.tpl.php**.

I have a custom content type "festivals\_events" and a cck field "field\_description". So, I created a template "field--field\_description--festivals\_events.tpl.php". But it is not working.

I tried to replace _ in field name with - as suggested in Template Suggestion, http://drupal.org/node/1089656, to become my template name file name as "field--field-description--festivals\_events.tpl.php" This too is not working.

I think it is definitely can be used as it is mentioned in Template Suggestion. What is wrong with me?

Thanks in advance.

# Answer
> 3 votes
Try "-" in the contact type name like **field--field-description--festivals-events.tpl.php**

**\[Edit\]**
You may also need a template suggestion in your theme.

```
function mytheme_preprocess_field(&$variables) {
    if($variables['type'] == 'festivals-events'){
        if($variables['element']['#field_name'] == 'field_description') {
            $variables['theme_hook_suggestions'][] = 'field__field_description__festivals_events';
        }
    }
}

```

---
Tags: nodes, entities, theming
---


# Question
Title: What permission is required to access node reference data?
I created a CCK field (`claim_category`) in a CCK type (`claim`), added a few `claim_category` nodes.

When I try to create a new `claim` node (`/node/add/claim`), admin can see the `claim_category` drop-down list fine. However, an authenticated user sees an empty drop-down list with no option in it.

What permission is required for an authenticated user to to access the drop-down list data (`claim_category` nodes)?

*Note:* CCK Content Permission module is not enabled.

# Answer
> 0 votes
After I add a dummy CCK field in `claim_category`, the list show up properly.

# Answer
> 0 votes
ohho,

I think you have not set view and edit - 'claim\_category' permission for authenticated user.

goto admin/user/permissions

set view and edit - 'claim\_category' permission for authenticated user.

---
Tags: entities, 6
---


# Question
Title: Calling theme_hook_suggestions inside template.php
I am using template\_preprocess\_block() to introduce a theme function like this:

```
$variables['theme_hook_suggestions'][] = 'block_system_main_front';

```

but adding MY\_THEME\_block\_system\_main\_front() to my template.php file does not change anything, MY\_THEME\_block\_system\_main\_front() is not being called.

How can I introduce a custom theme function using theme\_hook\_suggestions and then use it like I use theme\_image\_formatter() ?

# Answer
> 1 votes
`theme_hook_suggestions` is not for **function** suggestion, it is for template suggestion.

In your case:

```
$variables['theme_hook_suggestions'][] = 'block_system_main_front';

```

Drupal will try to load the file:

```
your_theme/templates/block-system-main-front.tpl.php

```

---
Tags: 7, theming
---


title: Override user pages with a view

text:
# Question
Title: Override user pages with a view
Is it possible to override a user page with a view? I would like to override the user page to show all the nodes created by that user.

# Answer
I found the answer to this!

In Views under relationship, select *Content: Author*

Then in under Contextual Filters select *Content Author UID* Use the following settings for Content Author UID:

* Relationship: Nodes
* WHEN THE FILTER VALUE IS NOT AVAILABLE: Provide
* Default Value / User ID from URL WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED: Specify Validation Criteria / Validator: User / Allow both numeric UIDs and string usernames

Then simply create a block and display it on the user page (Go to block settings and set the path to `users/*`

I hope that helps someone!
> 1 votes

# Answer
Views is not the right tool to use here, as views is for listing of content.

What you probably want is to use panels to take over the user page and display anything, like a view in it.
> 2 votes

# Answer
Might not be the answer but try this module http://drupal.org/sandbox/AshishThakur/1511158
> 0 votes

# Answer
There is a way to replace the content of user page with views page (Tested)

```
function MODULE_menu_alter(&$items){
  $views_router = menu_get_item('path/to/my/views');
  if( $views_router ){
    $items['user/%user']['page callback'] = $views_router['page_callback'];
    $items['user/%user']['page arguments'] = $views_router['page_arguments'];
    $items['user/%user']['access callback'] = $views_router['access_callback'];
    $items['user/%user']['access arguments'] = unserialize($views_router['access_arguments']);
  }
}

```

Flush the cache and check the views accessibility settings.

Visit the user page for effective results.
> 0 votes

---
Tags: views, users
---


# Question
Title: Is $page only an array important for theming purposes?
I know Wordpress theming, but I am a beginner with Drupal theming. Drupal render array totally confuses me.

1. Do all modules put their content in the `$page` array?
2. Is `$page` only an array that is important for theming purpose? If the answer is no, then what kind of renderable arrays are available in Drupal for advanced theming?

# Answer
There is just a type of render array, and it is the one described in drupal\_render(); the form API extends the render array with properties necessary to validate/submit a form element. The purpose of a render array is just to theme elements present in a page; it is not used for other purposes, if not rendering/theming.

The output of a module is always part of a render array, except when a module implements code similar to the following one.

```
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view() {
    echo "<html><head><title>Error</title></head><body><span>Error page</span></body></html>";
    drupal_exit();
  }

```

If you visit http://example.com/abc/def, there isn't any render array involved in rendering the page.
> 3 votes

---
Tags: theming
---


# Question
Title: Moving a contrib module from /modules into the sites/all/modules folder
I need to run a simple fix in my Drupal 7 website. The website administrator, not being a Drupal specialist, installed the SMTP module in the root /modules folder, instead of the /sites/all/modules folder. Now I need to upgrade the SMTP module and noticed the mistake. My first impulse was to move the SMTP folder from /modules into /sites/all/modules, and then proceed with the regular upgrade.

My question is: do you think that moving the SMTP folder from root /modules into /sites/all/modules could cause any problems, like data loss or website crash?

# Answer
> 6 votes
It’s OK (in most cases). Drupal 7 will find new destination of module after registry rebuilding. So, just move folders in proper destination and clear all cache.

It works for moving modules, but not for disabling and uninstalling. Don't remove module folder before complete uninstalling.

**Update:** I can move module folder even without disabling that module, because I use Drush for immediate cache clearing. In other situations it will be useful to disable module before moving.

---
Tags: 7
---


title: Drush and multisite config

text:
# Question
Title: Drush and multisite config
I have a new multisite instance with the Backup & Migrate module installed in `/sites/all/modules/`

When I run `drush` the `bam-*` commands don't show as available commands.

I have site aliases set up and if I run `drush @site-alias bam-destinations` as a test it does show the available backup destinations.

Is there a more correct way to show the list of available commands for all sites as well as site-specific commands?

# Answer
Did you try `drush @site help`? Simply running `drush help` will show only the globally-available commands; you must change your working directory to the folder with your settings.php file or use a site alias to select a specific site to see the help for drush commands defined in that site's module.

Sometimes, the Drush command cache can get in your way. Run `drush cc drush` to reset it. Since `drush @site bam-destinations` is working, this is probably not your issue.

If you are still having trouble after trying these things, also try upgrading to the latest version of Drush (HEAD of master), as some fixes that may be related have been committed post-Drush-5.4. Also try `drush @site help bam-destinations` and `drush @site bam-destinations --help`. If you're still having trouble, please post a bug report in the Drush issue queue.
> 3 votes

---
Tags: drush, multi-sites
---


title: load recent nodes with node_load()

text:
# Question
Title: load recent nodes with node_load()
How can I load recent nodes with `node_load()`?

I used the following code, but I can't edit the links because it creates a list where they are inside it. I want to load the node IDs, and then use `node_load()` to load each node.

```
$output = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = '%s' AND n.status = 1 ORDER BY n.created DESC"), story, 0, 10));
print $output;

```

How is that possible?

# Answer
> 1 votes
Using only `node_load()` you cannot get a list of the most recent nodes, as `node_load()` returns a single node object for the node that matches some criteria; it's not a function that returns a list of nodes.

The faster, but a little inefficient, way to get a list of more recent nodes is to:

* Get the list of node IDs associated with the most recent nodes
* Call `node_load()` for each of the node IDs obtained from the first step

You could use code similar to the following one.

```
   $nodes = array();
   $result = db_query_range("SELECT n.nid FROM {node} n ORDER BY n.created DESC", array(), 0, $number_of_posts);

   while ($nid = db_result($result)) {
     $nodes[] = node_load($nid);
   }

```

After that code is executes, `$nodes` will contains the `$number_of_posts`th recent nodes.

---
Tags: 6, theming, nodes
---


# Question
Title: conditional removal of a field in a view
I'm displaying the latest 5 nodes (teaser view mode) in a sidebar region using `views`. The nodes have an image field but I only need to render that on the first node on the list.

So, since the teaser view mode does include the image, I'm trying to remove the image from all nodes apart the first upon rendering.

I've tried the following in my theme's `template.php`:

```
function foo_preprocess_views_view(&$vars) {
  if (isset($vars['view']) &&
      isset($vars['view']->style_plugin) &&
      isset($vars['view']->style_plugin->row_plugin->nodes)) {
    $first = true;
    foreach($vars['view']->style_plugin->row_plugin->nodes as $node) {
      if (!$first) {
        unset($node->field_image);
      }
      $first = false;
    }
  }
}

```

But the image is still being rendered. I think that this has to do with the fact that I'm trying to temporarily remove the image from the wrong datastructure which represents the node state.

I then tried using the `hook_preprocess_node` with something like:

```
unset($vars['field_image']);

```

But it still has no effect. The image was still there.

How is this solved? And at which layer is it solved best?

I know I could simply hide via CSS by using the `.views-row-first` class but I don't think this is optimal.

# Answer
try hook\_views\_pre\_render() and unset the field there if you dont want to show it. THen in the view configuration set the field to "hide if empty".
> 1 votes

# Answer
Take a look at Views Nodes Split. Module Monday: Views Nodes Split gives more information about how to use the module.

> Setting up the module is simple: just turn it on, and build your View as you normally would. Then, click on the View's Format option and select the newly available "Splited Content" row style. While the grammar is awkward, the results are great: you can specify separate build modes and display styles for the first node and all subsequent nodes from a simple config screen. In fact, you can even adjust where the cutoff happens: you might want the first three nodes to display in full, for example. No other changes are needed for your View; this module's new row style handles the rest.
> 1 votes

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


# Question
Title: Cannot Find CSS Class For A Custom Block
Hello due to much help from here in the past im starting to theme whatever part of my drupal site that i like. Its great. Ive ran into a a strange one though. I have created a custom block (block 130). You can see it on top of my site

BBC Live Olympics | Add Olympic Comment | Football Livescore | OLB Olympics http://onlinebanter.com/latest

For some reason it doesnt have any div class Im trying to change the p bit.

Ive tried various things but still cant seem to find this blovk. Does anyine have any suggestions?

Thanks

# Answer
> 1 votes
You don't have a class, but you do have an ID so you can use:

```
#primary p {color:red;}

```

**Note:** there is also a nice module call block class (http://drupal.org/project/block\_class) that you can use

---
Tags: blocks, theming
---


# Question
Title: How can I re-format (not validate) the value of a field that a user inputs into a node?
I am using the Addressfield module to allow users to input addresses. I am then using the Location Taxonomize module to generate a taxonomy based on these addresses.

To make everything consistent, I would like to automatically capitalize the first (and only the first) letter of every word (I know there are exceptions where multiple words should be capitalized, but I am willing to deal with those manually).

How can I implement this?

# Answer
> 2 votes
In Drupal 6, you could do something with the nodeapi() hook, eg,

```
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)

  if ($node->type=='TYPEOFNODE' && $op == 'presave') {
    $node->field_WHICHEVERFIELD[0]['value']=ucwords($node->field_WHICHEVERFIELD[0]['value']);
  }

  // other nodeapi()ing goes here

}

```

In Drupal 7, you could use the node\_presave() hook with similar logic.

---
Tags: forms
---


title: My site thinks it's a new install

text:
# Question
Title: My site thinks it's a new install
I had an error (related to Date module I think? Can't remember.) on my site so I tried to do an update. Caused a WSOD so I svn reverted. Didn't help. Manually disabled each module in the database. Didn't help. Fixed some permissions. Helped... sort of.

Now I get this:

> Drupal already installed To start over, you must empty your existing database. To install to a different database, edit the appropriate settings.php file in the sites folder. To upgrade an existing installation, proceed to the update script. View your existing site.

Running the upgrade script gives this error:

> PDOException: SQLSTATE\[HY000\] \[2002\] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in drupal\_get\_installed\_schema\_version() (line 150 of /public\_html/includes/install.inc).

Any other page redirects back to install.php.

So it seems like it can see the database to know that it's not empty, but can't really connect to it... what does this mean? What do I do about it.

# Answer
> 3 votes
I figured this out. It's able to see the settings.php file but instead of the right database credentials it was showing this:

```
$db_url = 'mysqli://mynamedrupal:xxxxxxxxxxx@localhost/myname-drupal-6';

```

That's goofy! I'm not even using Drupal 6! There wasn't any updated version of this later in the file; this was the only database connection info. It makes sense that this was in here, since it was originally a D6 site that I upgraded, but it's unusual that it worked so long without an updated array of DB connection info.

So I pasted this in from another D7 install and changed the un/pw accordingly:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'myname-drupal',
      'username' => 'myname',
      'password' => 'xxxxxxxxx',
      'host' => 'server.host.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

I can't say for sure if this works because now I'm having different, unrelated problems. But I think this solved this particular issue, as far as I can tell, and now I'm on to troubleshooting the next thing. w00t.

---
Tags: 7, installation, configuration
---


# Question
Title: Set a page to show only to registered users
I have a website with two pages. The "home page" and a "notice page". The notice page should only be viewable to people who are logged in or people who have the role called "Basic User". I have created the role, but I cannot find how to set this notice page (basic page) to require log in.

Here is a similar question, but I think it is regarding drupal 6 and I know that a lot has changed when drupal 7 was released.

Set a page to be only viewed by users who are logged in

# Answer
There's a usable dev version of Node Privacy by Role for D7.

Alternatively, you could edit the templates for those pages to check a user's role before displaying the content. I can't really think of why you'd want to, but you could.
> 1 votes

---
Tags: 7, users
---


title: loading nodes with Ajax/jQuery

text:
# Question
Title: loading nodes with Ajax/jQuery
Assume that we have a list of titles on the left and a div on the right side of the page that displays posts. when I click one of the titles it first removes content of that div and then loads node content. how can I do this? is there any module or function to do that?

# Answer
You could look at the Quick Tabs and Vertical Tabs modules. Otherwise you could write your own custom module if you had super specific needs and are proficient with drupal menu callbacks and php and of course jQuery.
> 1 votes

---
Tags: theming, 6, javascript, ajax
---


# Question
Title: How do I add a password field on registration form?
I have a basic website, with nothing installed on it yet. My first task is to get my users to be able to register with a password. I see that certain "modules" will allow you to do this, but is a module really necessary to be able to register with a set password?

I'm using Drupal 7.

# Answer
Go to *Account Settings* (admin/config/people/accounts) and uncheck the *Require e-mail verification when a visitor creates an account* checkbox.

> With this setting disabled, users will be logged in immediately upon registering, and may select their own passwords during registration.

If you want both (Password field + email verification), use the User registration password module
> 11 votes

---
Tags: 7, users
---


# Question
Title: How to choose a CSS grid system for new theme?
I am going to make a new responsive theme based on an existing base theme for drupal 6. The theme need to be minimal but flexible. As there are many CSS grid systems to choose from, I've read that 960.gs has fallen out of fashion as it is too small for current monitors. So I'm wondering whether there are any important differences between fluid and non-fluid ones, and currently what are the best options available and why?

# Answer
> 6 votes
Ok, there is no single best answer. It really depends on your needs.

960.gs may be out of fashion, but you can use the Variable Grid System to make just about any grid you need (both fixed and fluid).

In my opinion, the difference between fixed with and fluid grid has more to do with the theme you want (and your art director). Not all designs will work with fluid grids, especially ones that require pixel perfection.

That said, there are techniques that you can use to have a fixed grid, but have it adaptable for different screens. Basically, you design a few grids with the link above, and then use CSS3 Media Queries to load the grid you want based on screen size. This is precisely what the Omega Theme does. I have good results with this approach (though with the Drupal 7 version), and highly recommend it rather than tacking on the grid to another base theme. I used Zen 960 a few years ago, and ended up fighting some of the automatic grid reassignments that it did.

If you go with Omega, just note that the grid-24 that it includes is slightly different than the one from 960.gs. This means that you can't use the 960.gs templates with Omega's grid-24. You can `hook_css_alter` in the sheets from 960.gs without any side effects (Drupal 7), or use other shenanigans for Drupal 6 to change the sheets you need.

If you really do need to retrofit an existing Drupal 6 theme (and can't use Omega), then I think I would sledgehammer in the multiple-grid approach that Omega uses directly into page.tpl.php.

---
Tags: theming
---


# Question
Title: Enable Relationships in Views with Entities?
I am creating some custom entities and one of them will need to contain a helper table to store a lot of data against one entity (event dates, prices, and tickets left). This is not a Commerce based app, we simply need to display the data appropriately as we receive it all from a third party service.

What I would like to do is rewrite the Entity implementation and not use Fields, but store this all as Properties, which will require its own table and fields with the proper foreign key back to the main Entity. Currently, it is all stored in Field Collections, which can be difficult to work with (Importing/Exporting the entity, or installing/uninstalling the module- FCs are just hard to script, attach, and add fields to in my experience).

So, assume:

* entity
* entity\_event

I can get the data in and out fine.

With Views, how do I tell the Entity there is a relationship available here by the ID? When I am searching them with Views, I need to allow a search by date, AND that the event itself has tickets left (tickets wont be a exposed filter).

I assume too, that when buildContent() is called on the Entity to view it, here I attach the additional data from the event table?

# Answer
> 0 votes
You will need to use (or override) the **views\_handler\_relationship** class to create the relationship, and also use **hook\_views\_data\_alter(&$data)** to tell views how to use the handler and with which tables/columns it applies.

---
Tags: 7, entities
---


title: Allows users to tag content in Drupal

text:
# Question
Title: Allows users to tag content in Drupal
I have what I thought would be an obvious question but after searching for an answer I can't find anything even close.

I would like a way in Drupal to let authenticated users "tag" existing site content by selecting from one of 12 available categories. (They won't need to add any of their own categories.)

The tags they associate with individual nodes should be stored in a separate table with their uid, the nid and the tid they selected. Later this can be used to show tag distributions for nodes, but that's not immediately needed.

What's the best way to do this? The users will of course not have edit permissions on the nodes, they just need to be able to tag them.

# Answer
If you have only 12, or some other manageably small number of categories, I would investigate the Flag module. Just set up flags named to your categories and you're off and running.
> 2 votes

---
Tags: 7
---


# Question
Title: Can I display Media Videos in a single "media player" block
I have several youtube videos listed on a page. I am currently loading them as Media Fields. What I would like to do is declare a single block (or perhaps a region) where the videos play no matter which video I select. SO rather than displaying the URL to a video, or the video itself, I want to display a play button.

Is there a standard way of doing this with Media, or do I have to create my own Javascript to insert the video into a "video player" block

# Answer
> 1 votes
You could create a View that makes a Block, and set it to display videos that meet whichever criteria. Or, you can just embed videos directly in a block with `embed` code. You can try the Video module or Video Embed Field to show videos from another source or from your side.

# Answer
> 0 votes
I think using embedded media field and media youtube modules will do.you have to create a block view of the respective media field content type.We have options either to display thumbnail or full video images.

---
Tags: files, media
---


# Question
Title: Restrict Location per Domain in OpenLayers
I have Domain Access and Open Layers running on a site. Think of it as a map-based Craigslist. Each city has it's own subdomain, offering location-based content.

Users create content with a location on each subdomain, and I need to make sure that content's location is inside a radius (say, within 50 miles of a centerpoint) for that subdomain.

How can I do this?

# Answer
I think you can do this with:
> 0 votes

---
Tags: 7, location, domain-access, javascript
---


title: Load nodes from specific content type

text:
# Question
Title: Load nodes from specific content type
Thanks to kiamlaluno♦ I can load recent nodes using node\_load() but how can I load recent nodes from a specific content type?

# Answer
You should always enclose the table names with curly brackets. That way table prefix (if any) will be added automatically. It's better to use that way all the time.

This is how your query should look like:

`SELECT `nid` FROM {node} WHERE `type` = 'page' ORDER BY `created` DESC`.
> 4 votes

# Answer
I found the solution:

```
SELECT nid FROM node WHERE type = 'page' ORDER BY created DESC

```
> -1 votes

---
Tags: 6, theming, nodes
---


# Question
Title: Can anyone give me an example of a seperator used in table style in views
I am not sure what seperator does. I basically want view of the node:title, and the node body in the same column of a table. How can I acheive this?

# Answer
Dunno about drupal 7 but in in 6 youd go to your View, then View Style, select table, click on the wee wheel for options, and then select which coloum you want your fields in.
> 1 votes

---
Tags: views, theming
---


title: Why JS doesn't work on a saved page?

text:
# Question
Title: Why JS doesn't work on a saved page?
I've tried to save /admin/structure/block page and open it with Firefox 14.0.1. After this I cannot drag blocks. Why is that? There are no errors in the console. How should I debug such behavior? I need this to better understand why doesn't Drupal work for JS-loaded content. The symptoms look similar.

# Answer
The Drupal's jquery.once.js is to blame. Deleting every \*-processed class worked.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Views Taxonomy Term Argument With Multiple Terms
Hello I am having a torrid time creating a views block. Let me try to explain without rambling on about nothing as I usually do.

I have a content type (links) which uses the same vocab as my other content type (posts) When viewing a Post I was hoping to display any links that have the same terms.

Ive set it up with an Argument Taxonomy: Term ID. It all works as hoped when I have just ONE term on a post but when I have more than one term things start to get a bit strange.

Actually I should mention that I am using Load default argument from node page and just doing it on term id. I am not using Allow multiple terms per argument box. this returns no results (for nodes with multiple terms)

If I change the Argument type: to term id's seprated by ....+ etc I do get a return but it only shows links for one of the terms. Funny enough the term results are for the term that I dont want to use. I have changed the term weights and everything to try and change it to show the links for the term I was hoping for but I dont seem to be able to influence what terms results appear in the views box I have made.. Its got me tearing my hair out.

Can anyone understand my gibberish and offer any solutions?

# Answer
I think I have sort of worked out a solution. It displays correctly in the Views preview but not on the node itself. Maybe this will help though.

View settings:

Create a Block. Configure Block to display on content of type Post. Configure settings of View:

## Fields

* Content: Title

## Filter criteria

* Content: Published (Yes)
* Content: Type (= Links)

## Contextual filters

* (field\_tags) Content: Title
    + Using relationship: Term

## Relationships

* Content: Taxonomy terms on node (term)
* Taxonomy term: Content using Tags
    + Using relationship: term

In my preview, when I enter the title of a Post as the contextual filter, I get a list of all the links tagged with the same tags as the Post. For some reason, when I view the actual Post it doesn't work but that might just be a caching issue or something on my end?
> 1 votes

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


# Question
Title: Alter menu structure when using Superfish menu
I am using Superfish menus. I wanted to add a `<span>` tag before each `<a>` tag for menu links. I tried the following code:

```
function mytheme_menu_link($variables) {
    $element = $variables['element'];
    $sub_menu = '';
    if (empty($element['localized_options'])) {
        $element['localized_options'] = array();
    }
    $element['localized_options']['html'] = TRUE; //let l function know that our link title includes html
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '<li' . drupal_attributes($element['#attributes']) . '><span>' . $output . "</span></li>\n";
}

```

but it did not take any effect. Since I am using Superfish menus do I need to write any other code?

# Answer
The Superfish module bypasses the usual Drupal theming hooks for menus and implements its own. You will need to override the theme\_superfish() function in order to change the HTML around those menu items. Copy that function out of `superfish.module` into your theme's `template.php` file. Replace the word "`theme`" in the function name with your theme's machine name, and make your edits.
> 9 votes

# Answer
You can easily do this via the administration interface. You could also override theme\_superfish\_build(), but there's a simpler solution exactly for that task:

1. Go to `admin/structure/block`, search for the given Superfish block, and click configure. E.g. in my test Drupal, I'll edit *"Superfish 4"* block (in my case the path is the following: `admin/structure/block/manage/superfish/4/configure`):
2. Scroll down to *"Advanced HTML Settings"*, expand the fieldset, and below the *"HTML Wrappers"* sub-fieldset, there will be a field called *"Around the hyperlinks"* (NOT the *"Around the hyperlinks contents"*), type in the following:

```
<span class="this-is-your-span-class">,</span>

```
3. Save block, and you're done.

---

# Screenshots

## BEFORE

## AFTER
> 4 votes

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


title: drush aegir and drupal

text:
# Question
Title: drush aegir and drupal
I have created a platform on my aegir dev server and I found myself wondering once the platform in drupal7 is installed is there a way to create websites using that platform via the commandline.

# Answer
> 6 votes
Yes there is: it's a two or three step process, but automatable.

Step 1) Create a Drush alias, or in Aegir terminology, 'context' for the site using `drush provision-save (arguments)`

Step 2) Install the site using `drush @(site context name goes here) provision-install`

Step 3) (optional but recommended) Verify the platform in the Aegir interface to have it automatically detect the site and 'import' it into the frontend so that you can do other things to it later via the web interface. You can also run this verification from the command-line with `drush @hostmaster hosting-task @(platform context name goes here) verify`

For specifics on the syntax of provision-save etc, see my article, "Manage your Aegir system from the command line": http://mig5.net/content/manage-your-aegir-system-command-line.

---
Tags: drush, aegir
---


# Question
Title: Minimum entity properties for field_attach_update()?
*Question:* What are the properties that are essential to be defined in the entity passed to `field_attach_update()` for the function to update the appropriate fields (and not silently do nothing)?

This is not detailed in the field\_attach\_update API page and, in articles I can find written about it, it seems that what I have defined above (ID, bundle, field data to update) should be enough.

---

*Context:* I'm using `field_attach_update();` to keep some fields on seperate entities in sync with each other, using code like this:

```
        // Load entity, get entity type data data...
        $entity = array_pop(entity_load($entity_type, array($entity_id)));
        $entity_info = entity_get_info($entity_type);
        $id_key = $entity_info['entity keys']['id'];
        $bundle_key = $endpoint_info['entity keys']['bundle'];

        // Do stuff with the entity, modify field_some_field
        do_stuff($entity);

        // Build stripped down object containing only essential data
        $lightweight_entity = new stdClass();
        $lightweight_entity->$id_key = $entity->$id_key;
        $lightweight_entity->$bundle_key = $entity->$bundle_key;
        $lightweight_entity->field_some_field = array(
          'some_key' => 'some_data'
          'another_key' => 'more_data'
          );

        // Save it
        field_attach_update( $entity_type, $lightweight_entity );

```

This did work fine, but has recently (since updating to Drupal 7.14 I believe) been silently failing. No errors, nothing in logs - but no updates to the fields within Drupal and no changes to the field\_data\_field\_some\_field in the database. It seems like field\_attach\_update() isn't so much failing, as judging that it doesn't have any work to do. My theory is, that something is missing from the $lightweight\_entity object, causing field\_attach\_update() to dismiss it as not a match or not a change.

(I'm piping in an entity object that is as simple as possible, partly because this sync function needs to run often and on many entity types, and partly because I have found that sending the whole original modified $entity object to field\_attach\_update() can result in PDO database fatal errors due to issues like this one, so simplicity is key. I'm using field\_attach\_update because it's syncing fields rather than updating the *entity* \- new revisions data doesn't make sense in this specific context - from a user's perspective, the content hasn't been revised, and reverting the sync to become out of sync wouldn't make sense)

# Answer
**EDIT** \- Actually, it turns out that the core team have decided that passing in anything less than the whole entity to `field_attach_update()` is officially Wrong and not to be done. See http://drupal.org/node/1483736, if there is a file field (therefore, also media fields, image fields), and you update using `field_attach_update()` without including all the file field data, the file fields will be wiped.

So the correct answer in terms of the thinking of the core team is actually, all of them. As far as I know, it's only file fields that break like this, so you theoretically, in cases where passing in the whole entity object breaks, you could pass in entity id and bundle as below plus any previous file fields, but there's no guarentee nothing else would break.

---

**Original answer -** Actually after more testing and debugging, that first article seemed to have it spot on. The entity needs:

* The entity id (as above)
* The bundle (as above)
* The field data, keyed with *language* (even if not applicable) and *delta*

(basically, so there's enough data to identify the entity and field instance)

...so my example above should have had:

```
$lightweight_entity->field_some_field[LANGUAGE_NONE][] = array(
      'some_key' => 'some_data'
      'another_key' => 'more_data'
      );

```

And if the field name is dynamic, needs curly braces:

```
$lightweight_entity->{$field_name}[LANGUAGE_NONE][] = array(
      'some_key' => 'some_data'
      'another_key' => 'more_data'
      );

```

Another relevant thing to note is, on a multi-item field, it replaces all items with what is entered here, regardless of what you put for the delta. E.g. if you have 5 items already, and try to add a sixth like this:

```
$lightweight_entity->{$field_name}[LANGUAGE_NONE][6] = ...

```

...it'll wipe the other 5. So, for multi-item fields which can already have data, you need to populate the mini-entity with all the items for that field before saving, for example:

```
if (!empty( $entity->{$field_name}[LANGUAGE_NONE])) {
  $lightweight_entity->{$field_name}[LANGUAGE_NONE] = $entity->{$field_name}[LANGUAGE_NONE];
}
$lightweight_entity->{$field_name}[LANGUAGE_NONE][] = ...

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: if title available print $title if disabled print somthing else
I use advanced forum but it uses default Drupal title method.

I know there is a module called Comment subjects for this purpose but I need to do it in this way.

I would be grateful if anyone could help me.

```
 if $title >avalible print $title
 if $title disabled print <h3><a href="#<?php echo $comment->cid; ?>"> Re: <?php print $node->title ?></a></h3>

```

OR

```
 if > node print $node->title
 elseif comment $print <h3><a href="#<?php echo $comment->cid; ?>"> Re: <?php print $node->title ?></a></h3>

```

# Answer
Found the Solution.

Go to -\> (advanced\_forum/styles/naked/advanced-forum.naked.post.tpl.php)

```
  <?php if (!empty($title)): ?>
    <div class="forum-post-title">
      <?php print $title ?>
    </div>
  <?php endif; ?>

```

Then replace it with:

```
<?php if (!empty($title)): ?>
    <div class="forum-post-title">
        <?php print $title; ?>
    </div>
<?php else: ?>
    <div class="forum-comment-title">
        <h4><a href="#comment-<?php print $comment->cid; ?>"> Re : <?php print $node->title ?></a></h4>
    </div>
<? endif; ?>

```
> 1 votes

# Answer
When you disable the title tag does the node have value? Because if it does, all you need to do is adding an control statement.

```
if ($node->title[array values] == the disabled value) {
  // What I need to print here.
}
else {
  // Print the rest.
}

```
> 0 votes

---
Tags: nodes
---


title: Blank browser after clearing the cache

text:
# Question
Title: Blank browser after clearing the cache
I migrated a site from windows xampp to ubuntu. It was working fine. But once I cleared the cache, the browser is showing blank screen.I tried going to different urls . I also tried clean urls but nothing is coming. All I can see is a white/blank browser.

# Answer
The White Screen of Death (Completely Blank Page) is a good starting point to takle down the problem.

For D7, **extension=php\_domxml.dll** in php.ini must be commented out. With that dll enabled, I got a blank screen too in Windows.
Check with your php configuration in your linux server.
> 3 votes

---
Tags: caching, wsod
---


title: More info for autocomplete choices?

text:
# Question
Title: More info for autocomplete choices?
When I have an entity reference field with an autocomplete widget, is there a way to add a field to the info that appears in the autocomplete choices? Seems like the default field is Title, but this in my case might be ambiguous.

# Answer
> 6 votes
An easier solution is to modify the 'label callback' property of the node entity.

```
function mymodule_entity_info_alter(&$entity_info) {
    $entity_info['node']['label callback'] = '_mymodule_label_callback_set';
}

function _mymodule_label_callback_set($entity, $entity_type){
    if($entity_type == 'node' && $entity->type == 'my_node_type'){
        //Compute new label here
       $label = 'test';
       return $label;
    }
}

```

# Answer
> 3 votes
You must create a selection entityreference plugin. In you can see an exemple in selection directory of plugin directory of entityreference module.

# Answer
> 2 votes
For the non-coder solution that only affects the field:

What you could do is create an entity reference list from a view and populate your widget with the view.

Create a new view Untick Create a block and Create a page Then click continue and edit. That should get you to the master view.

Click Add to add a new display and choose entity reference. Give your display a easily recognisable name. Add your fields/ filters etc and order them as required. I usually change the items to display under pager to display all items, but I'm not sure how required this is.

Under the Format heading beside Format, click settings and set your field(s) that are to be searched when auto-completing. Under the Format heading beside Show, click settings and set your fields to be inline. Save your view.

Now head over to edit your entity reference field. Assuming you already have your field pretty much set up the only bit you might need to change is under: Entity selection mode Choose: "Views: Filter by an entity reference view" Assuming your field reference target type and view list match up you should get a dropdown appearing under "View used to select the entities" with your newly created view listed in there. Choose it and save.

Now all going well when you add a new entity your field reference will contain a list of entities based on your view.

# Answer
> 0 votes
You can create a "Reference" display on a view which you can use. If you created this, go back to your autocomplete field and select the created reference display. But with this, you only alter the text which is displayed in the autocomplete box. The search still goes on the node title.

---
Tags: ajax, entities
---


title: show anonymous users in a view

text:
# Question
Title: show anonymous users in a view
I was wondering if there was a method to show anonymous users in a view. I have looked at various alternative such as the link below for showing anonymous users. http://scito.ch/content/count-access-statistics-anonymous-users-only-drupal-7. I did construct a view for the number of registered users but am having a problems showing just anonymous users in a view

# Answer
> 2 votes
There is (and should only ever be) **one** anonymous "user" for your site. That will be in your db users table as uid 0.

*If* you'd like to count the number of anonymous users that are visiting your site at a certain time you can adapt (to a custom module) something like this that is used in the admin\_menu module (this is from admin\_menu.module 7.x.3.0-rc starting around line 395:

```
function admin_menu_get_user_count() {
  $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
  $count_anon = admin_menu_session_count($interval, TRUE);
  $count_auth = admin_menu_session_count($interval, FALSE);

  return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}

function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
  $query = db_select('sessions');
  $query->addExpression('COUNT(sid)', 'count');
  $query->condition('timestamp', $timestamp, '>=');
  $query->condition('uid', 0, $anonymous ? '=' : '>');
  return $query->execute()->fetchField();
}

```

And then output the return values. If you want to count the all time number of anon visits to your site than that is a different story. If so, please update. Thanks.

---
Tags: views, users
---


# Question
Title: Understanding Drupal's session management and user authentication
I have a requirement to replace the default user authentication with the authentication of a central server, i.e., the SSO server.
By debugging Drupal, I learned that all the session management happens in the `includes/session.inc` file. I want to do authentication as shown in the image:

**SCENARIO: Login**
The details of the steps would be as follows:

1. Replace the login form to submit the username and password to the SSO server (**not on Drupal**, but on .NET).
2. Authenticate the user on the SSO server using that site's database, and send a response back to some custom PHP page of *my website* (or a form by a module?).
3. Using the response, identify the user in the *users* table, and create a session for that user without checking for the password (as it would mean double authentication). By default, Drupal sets a cookie with the name of the `$insecure_session_name` variable and the value `$sid`. I want Drupal not to set the cookie here but instead send the values of variables to the SSO server.
4. The SSO server will take the values, create a cookie, and drop it in the domain `domain.com` (to remind both `my website` and `sso server` are on the subdomain of the main domain, which is not in Drupal). Then, the drupal site can log in by using that cookie.

I know it is a tough ask, but I am just looking for pointers on how to start. as they say, "you should not hack the core". So, my questions are:

1. Where should I look to understand how Drupal authentication and session management works in depth?
2. Is there a way I could call the functions in `includes/session.inc` using hooks (as the comments with functions say "for internal use only/not to be modified")?

**NOTE:** I'll be using the same method to register the user so that the record remains in the central database of the SSO server. And during that will put in some junk password for the same user in the Drupal site's database (as the password will not be checked during login).

# Answer
> 17 votes
Drupal supports *external authentication*. There are many alternatives authentication modules for Drupal, such as OpenID (included in core), OAuth Connector, or LDAP. Learn more about how Drupal authentication works; the best would be to look at the OpenID and OAuth modules, and to the core login form submit callback. But, AFAIK, they always start the normal Drupal session after a successful authentication.

For session management, Drupal plugs into PHP session handling and register it own handlers. The Drupal session backend is itself pluggable, you can set the `session_inc` variable to the path of a file providing alternative implementations of the functions found in `includes/session.inc`. The memcache module use this to store session in memcached.

For references, the OpenID module handle successful authentication in `openid_authentication()` which itself *ceats* and call the user login form submit handler (ie. `user_login_submit()`). This submit handler itself is simple, it loads the successfully authenticated user with `user_load()` into the global `$user` variable, it then call `user_login_finalize()` which handle session, login timestamp in the `user` table and invoke `hook_user_login()` implementations.

Another option is the use the `user_external_login_register()` function. The function will log an external user in. It also creates a local user if needed. If you need more control on local user creation, you can always use `user_save()`, `user_set_authmaps()`, `user_login_submit()` and `user_external_load()` from you custom call, using `user_external_login_register()` as template of what needs to be done.

# Answer
> 1 votes
user\_authenticate() APi might come in handy here.

> 3.Using the response, identify the user in the *users* table, and create a session for that user without checking for the password (as it would mean double authentication). By default, Drupal sets a cookie with name of `$insecure_session_name` variable, and with value `$sid`. I want Drupal not to set the cookie here, instead send the values of variables to SSO server.

EDIT : Once SSO server returns with true use this API to login the user which will automatically take care of sessions for you. I think its better if you use `user_authenticate()` instead of creating sessions by yourself. It shouldnt make a problem even its a double authentication as long as valid p-assowrd is provided.

Am not sure of 4. Do you want the cookie to be visible in both domains ? If so then in settings.php initialize `$cookie_domain` to the domain. Then cookies in subsite will be available in parent site.

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


# Question
Title: How to export complete products data to csv file
We have a Drupal Commerce site, and need to dump all the products data into another CMS. I checked the question, How to export drupal commerce products?

After trying the Views Data Export module, I didn't find any option for CSV, Excel in the display.

What am I doing wrong? I would like to export data to a CSV file or any other document so that I can easily import those products into Magento.

# Answer
> 2 votes
Try **Views Bonus Pack** module too. You can see an option "Data Export" while adding a display in the view.

---
Tags: views, commerce, importing-exporting
---


# Question
Title: I18n translation of site_name not working
I have installed i18n, changed `settings.php` according to this guide, set language detection to url and cleared cache.

Then on site config page, I set the url prefix to English and all UI changed to English. Then I updated the Site Name to something English.

Then I repeated the above steps for a local language.

But it looks like changing the url path prefix each time gives me identical results regarding Site Name, i.e. the Site Name is changing each time I update it, no matter which language path is chosen.

What am I doing wrong?

P.S. In table "variable" the site\_name is just one. I never used `i18n` before, no idea how it should look here.

# Answer
To translate a Drupal 7 Site name you have to activate `Variable translation` module (which is in the same package as i18n) and the required ones (like `Variable store`).

After you install these modules, go to `Configuration -> Multilingual settings -> Variables` tab and choose **Site name** (`?q=admin/config/regional/i18n/variable`),Then go to `Configuration -> System -> Site information` (`q=admin/config/system/site-information`) and select the language you want. Change the **Site name** field and save.

You'll find the translated site name in `variable_store` table.
> 9 votes

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


title: Why do modules have bug reports?

text:
# Question
Title: Why do modules have bug reports?
A good question was raised in this comment by EGHDK:

> **Why do these modules have bug reports**. Shouldn't this be a simple task for a module to complete with no errors?

He was referring to limiting the viewing of pages to users of a certain role, but the question applies broadly.

# Answer
There's a big difference between creating a custom module for just one site (your own, let's say) and creating one that will be able to be used on many different sites.

For example, let's say I want to limit access to a certain content type to only users of a certain role. Let's say that content type is 'awesome\_thing' and the role is 'awesome\_person'. There are two ways to go about this.

* My own module that no one else will ever see or use

This would probably consist of something like a hook that gets called for each page, examines the $node object to see if it's 'awesome\_thing' and then, if it is, examines the $user object to see if it's an 'awesome\_person' and, if so, loads the page or whatever.

* A module that is fit for contribution to d.o contrib

This would have to include a configuration interface that allows users to specify which content types they want to restrict, and which roles they want to allow on those content types. If there's more than one combination of role and nodetype then you have to deal with that. Then, since you've given a mouse a cookie, people are going to have feature requests, or maybe they'll write patches that add features and you think they're cool and you want to integrate them into a new version of your module.

Then say your module has a dependency on another module for some of these features, or your naming conventions conflict with another module's. On most sites this won't be noticeable so you probably wouldn't ever encounter it as a problem just on your own site. But by the law of large numbers, if you let a whole bunch of people use your module, they're more likely to discover corner cases where things work in unexpected ways than you are to think of every possible use case.

And then someone might look at your module and see that you violated a coding standard or namespace convention. Or they might see that you used 5 lines of code to do something that could be better done in 3 lines, or that you did something that's going to be expensive on performance if the module is used on a large-scale site with higher traffic than yours.

The tl;dr is that writing your own snippet for your one little use-case is exponentially less complex than writing, say, a patch for public consumption which itself is exponentially less likely than a full-blown module to both contain bugs and to have its existing bugs noticed and called out.
> 9 votes

# Answer
I have been involved with the F/OSS community for 20+ years, and it has a dirty little secret:

*There is often very little incentive for the original authors to maintain code unless they are actively using it themselves or are affected by bugs themselves.*

I have several patches on issues that have sat for well over a year. There are also some really serious problems (for some people) in core that have patches that won't get committed.

When authors are committed to projects, they grow. When they get help they grow. When they encounter bugs that may affect them down the line, they accept patches.

When they don't use projects anymore, they stagnate. When they move onto other things, they die.
> 7 votes

# Answer
Inherently humans are flawed, humans write code, therefore code is flawed. This creates bugs.

Personally I suffer from "can't see the wood for the trees", when I code a new module I find it difficult to find every single use case for the module therefore I don't think of every issue that might crop up.
> 2 votes

# Answer
> Why do these modules have bug reports. Shouldn't this be a simple task for a module to complete with no errors?

I disagree that creating a module without errors is that simple, if not in the cases the module's code is really simple.
For that to happen, you should test the module in different conditions, which would also mean to test it in a test site running other modules as well, and with different versions of those modules. There are so much modules that is impossible to test all the possible combination of modules, especially because it's not a matter of testing the module you wrote with any combination of two other modules. Theoretically, you should test your module with a combination of infinite modules.

Writing tests for your module helps fixing the errors in the module you are developing, but that doesn't catch all the possible errors caused from the combination of two running modules.
If the test infrastructure used on Drupal.org allows you to do that, you can test your module requiring another module to be installed, but it would be up to you to decide which other module you want installed during the test, and you cannot foresee any possible problem with other modules. Also, you cannot test your module with random combinations of modules, considering that the test servers are thought to test not just your module, but all the modules hosted on Drupal.org.
> 2 votes

---
Tags: debugging, community-official-site
---


# Question
Title: Add line item quantity in block-commerce-cart-cart "title"
I'm making the cart-content div hidden as the default (in the sidebar shopping cart block), only the title will be visible, when the user hovers on the block-commerce-cart-cart the cart-contents div will be visible to them. How do I show the user how many items the got it their cart when only the block-commerce-cart-cart is visible, which means adding the line item quantity into the header. Can anyone please help?

# Answer
Here's a quick way using `hook_block_view_alter()`:

```
function MYMODULE_block_view_alter(&$data, $block) {
  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    global $user;
    if ($order = commerce_cart_order_load($user->uid)) {
      // Count the number of product line items on the order.
      $wrapper = entity_metadata_wrapper('commerce_order', $order);
      $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      // If there are more than 0 product line items on the order...
      if ($quantity > 0) {
        // Use the dynamic menu item title.
        $data['subject'] = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping cart (@count items)');
      }
    }

  }
}

```

The above borrows code from `commerce_cart_menu_item_title()` to get the cart quantity, so if that's the string you want to output you can just call that function directly and not bother with re-implementing the code, in which case it would be as simple as:

```
function MYMODULE_block_view_alter(&$data, $block) {
  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    $data['subject'] = commerce_cart_menu_item_title();
  }
}

```

The default return from `commerce_cart_menu_item_title()` will be at least 'Shopping Cart' (if the cart is empty) so this method should be pretty bulletproof.

Make sure you set the title of the block as an empty string on the block admin page (so the altered subject is used instead of a custom title) and that should work fine, e.g.:
> 9 votes

# Answer
I just tried this after I posted a bounty, and this works, but it's a very quick and easy (and dirty) way to do this. The trick would be to create a custom template for your view: `views-view--commerce-cart-block--default.tpl.php`

And on top of that template put this PHP code:

```
$num = 0;
if (count($view->result)) {
  foreach ($view->result as $view_result) {
    if ($view_result->commerce_line_item_field_data_commerce_line_items_quantity) {
        $num += $view_result->commerce_line_item_field_data_commerce_line_items_quantity;
    }
  }
}

```

`$num` should now contain the total of all quantities of all products in the cart.
> 0 votes

---
Tags: 7, commerce
---


title: media module for drupal 6

text:
# Question
Title: media module for drupal 6
I only see a Drupal 7 version for the Media module. On usage statistics I do see some Drupal 6 users using this module.

Is there anyway I can use this module with my drupal 6 install

How difficult would it be to port this module to Drupal 6 for a developer very experienced with Drupal 6 and somewhat with 7.

Is there any initiative to do this?

# Answer
> 4 votes
There is/was a development effort underway to backport the module to Drupal 6.

You can find the dev version (media 6.x-1.x-dev) here, but it hasn't been touched since February 2011.

The issue queue is also empty so it doesn't look like there's a lot going on with it. It might give you a place to start coding it yourself though

---
Tags: 7, media
---