# Question
Title: Strange disappearing <p> problem with Drupal 7
In CKEditor, source view, I see \<p\> tags around my paragraphs. That's great, makes sense. However when I view the node, the \<p\> tags are gone, replaced with \<br\> tags, thus killing the margins and cramming everything together. Re-editing the node brings the \<p\> tags back again in CKEditor.

I have tried changing the text format to disable "Convert line breaks into HTML", but of course that just removed *both* \<p\> and \<br\> tags, making one huge paragraph.

How do I prevent this and preserve the \<p\> tags?

# Answer
> 2 votes
Ah, I found it. In /admin/config/content/formats/filtered\_html, I needed to add \<p\> to the list of allowed HTML tags way at the bottom of the page. I'm not sure how/why this problem didn't show up previously...but this solved it.

---
Tags: nodes, wysiwyg, input-formats
---


title: Use arguments for drupal views 3

text:
# Question
Title: Use arguments for drupal views 3
How do you structure and use arguments in a view using the Views UI in Views 3

# Answer
> 0 votes
Arguments in Drupal 7 are the same as contextual filters. Contextual filters are associated with the path of the view (or the view's page). With these, we give a basic determining factor as to how we want to narrow down the view's output. It can be set up on what ever you want it to be. One of the simple ways to do it is by content type or user name. Check out this page it explains it well. http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments. I also found these vids while searching on relationships and contextual filters (arguments). Check them out they put a lot of things in perspective and teach you how to use them both.

Drupal 6:
http://gotdrupal.com/videos/drupal-views-relationships
http://drewish.com/node/127

Drupal 7:
http://vimeo.com/22100751

---
Tags: views
---


title: Could a content type be corrupt?

text:
# Question
Title: Could a content type be corrupt?
I just update a site from Drupal 7.14 to Drupal 7.15 and made some other modules updates.

One of the content I have created in the site is **Inmuebles**

The site have around 200 nodes of the Inmueble type. All of them are shown fine. But if I tried to **edit** them I get a blank page (nothing at all).

I tried to **Edit** the content type Inmueble itself and I get a blank page.

I tried to **Manage the Fields** and I get a blank page.

I have no problems with other content types, just with this one.

I guess this content type has a mis-configuration but I see no way to fix it if I can't access to modify it.

If I delete the content type because I will delete the nodes as well, then I can't do that.

What can I do? I have Drush installed, just in case it helps to fix this.

**UPDATE**

**Found the problem (but not the source of the problem)** *It was a problem of memory size. I had to set the memory size to 512 to get the content type loaded. But this is not normal anyway. The page takes 1 minute to load... and why does this content type need this much memory to work fine. How can I fix this?*

I enabled `Display query log` , `Display memory usage` and `Display memory usage` Now if I edit a node I get this summary report:

> Executed 731 queries in 555.96 ms. Queries exceeding 5 ms are highlighted. Page execution time was 3058.65 ms. Memory used at: devel\_boot()=2.08 MB, devel\_shutdown()=135.13 MB, PHP peak=137.25 MB.

# Answer
You can export all the nodes of content type "Inmuebles" with the drush command

```
drush -u 1 ne-export --type=inmuebles

```

Then maybe try deleting the content type and creating it again.

Although it doesnt make sense for a content type to just get corrupt, maybe if you check your error reports or apache log you will get a better look.
> 0 votes

---
Tags: 7, nodes
---


title: Add active class to link <li> using l()

text:
# Question
Title: Add active class to link <li> using l()
Seems so elementary but how does one get the active state onto the `<li>` of a link when manually using the l() function?

```
<li><?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?></li>

```

The above of course outputs the link in a list item with an active class on the link if the page is current, but how do I get that class onto the `<li>`?

# Answer
You can't. The `l()` function is only responsible for rendering the *HTML link*, it has no concept of the tag it's being wrapped in (or indeed if it's even being wrapped in another tag at all).

The simple answer based on your question is to add it manually:

```
<li class="active"><?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?></li>

```
> 7 votes

# Answer
menu\_get\_item() returns the current active menu item. So you can decide on that, ej:

```
$classes = '';
$path = 'my/hapiness/complete';
$current = menu_get_item();
if ($current == $path) {
  $classes .= 'active';
}
print "<li class='$classes'>" . l(...) . "</li>";

```
> 3 votes

# Answer
```
l('<link text>', '<link path>', array('attributes' => array('class' => array('class-a', 'class-b'))));

```
> 2 votes

# Answer
```
$output = '';

$submit_links = array();

$outp = array('0'=>10, '1'=>'20');

foreach ($outp as $key => $value) {
  // if you have dynamic links
  $submit_links[] = l(t('LINK TEXT HERE'), 'node/'. $value, array('attributes' => array('target'=>'_blank', 'class' => 'menu',), 'html' => TRUE));
}

$output = theme('item_list', array('items' => $submit_links));

return $output;

```
> -2 votes

---
Tags: 7, navigation
---


title: Undefined variable node in Drupal 7

text:
# Question
Title: Undefined variable node in Drupal 7
I am using zaptech theme in Drupal 6 while I am upgrading existing site to Drupal 7 it give me the error`: Undefined variable: node in include()` ,`themes\zaptech\page.tpl.php` can anyone tell what the solution for the node object

# Answer
Remove it unless you have an automatically loaded node associated with it.
> -1 votes

---
Tags: 7
---


# Question
Title: Do we really need Blog module in Drupal 7 (and 8)?
In Drupal 7, the Blog module do not have any option to change the URL. Because I want a different URL, I build blogs without the Blog module. For blog pages, I make it using Views and theme modification. I find it more flexible that way than using the Blog module. Nothing less except more flexible and extensible because it using generic approach.

I stumbled upon the Blog module for Drupal 8. I just wonder why the Blog module still exist. Why are there people still building it, if we can building it with the available modules and theming?

Is there anything good I missed in the Blog module?

# Answer
I suspect the Blog module exists for people who used it with Drupal 5 and 6, and are upgrading sites.

Personally, I never found the blog module of much uses. Typically, clients want something different about their blog, so I just roll my own with custom content types, Views, Panels, and custom blocks (as needed).
> 4 votes

---
Tags: nodes, 8
---


# Question
Title: how to add .install file to the new feature folder?
I have created new feature and needs to add .install file to create new table like create new module way

but the table have not been created

can you advice me with the right way to do or i have to create a new module along with the feature thanks in advance

# Answer
If you stay out of the files that Features generated, you can add code to the (Features generated) module the way you normally do things.

The problem is that your module is already installed when you're adding the schema via .install. You'll need to implement hook\_update\_N and add the tables using db\_create\_table. Run `update.php` or `drush updatedb` and your schema should be created.
> 3 votes

---
Tags: 7, features
---


# Question
Title: Is Drupal appropriate for what I want to do?
I am building a simple portfolio site for a friend. The vast majority of the site will be static, but I'd like to implement a kind of news/mini-blog on the front page, just two divs where he can update the site with his latest news.

Is Drupal overkill for implementing this kind of thing? Moreover, how simple would it be to set up; I have no CMS experience whatsoever.

# Answer
f you don't have any plans to expand the site in near future, then Drupal is an overkill.
The whole system is just too big for your purpose, and offers lots of functionality your friend won't ever need: permission system, roles, user profiles, content types, fields, forum, and comments. Especially as you don't have any CMS experience, Drupal will take the most time to setup, and you will need to learn a lot during the process.

I suggested WordPress because it is generally used for such websites by designers, takes less time to setup, and there are much more available themes and non-developer user tutorials. IMO, this would be the fastest option to setup.

Lastly, a custom CMS might be the best fit for this. If you don't have any ideas what to use, take a look at these frameworks: Codeigniter, Laravel or Yii.

Or, if you want to make it fun for you, use some micro framework: Flight (PHP 5.3+), or Slim (PHP 5.2/5.3). Pair it up with some tools/libraries for ORM/AR like Paris and Idiorm, RedBean, and/or an "unframework". If you want to get really fancy, add an MV\* JS library like Backbone.
> 4 votes

---
Tags: nodes
---


title: drupal 7: include javascript with rules

text:
# Question
Title: drupal 7: include javascript with rules
I have: drupal 7 - php module enabled - rules module enabled

On one of my rules I have the action: custom php code

when I enter `<?php echo 'test code'; ?>` it correctly shows the text

I want to include javascript, I've attempted:

```
<?php
    drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
    drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
?>

```

and

```
<?php
echo '<script src="http://www.googleadservices.com/pagead/conversion.js"> </script>';
?>

```

but when I view the source, there's nothing included. It's somehow stripped out or something.

What am I doing wrong? Is there a better approach?

Thanks for your advice

# Answer
You can use hook init to check for the path and add JavaScript in custom module.

```
<?php

function yourmodule_init() {
  if (arg(0) == "checkout" && arg(2) == "complete" && is_numeric(arg(1))) {
    drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
    drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
  }
}

?>

```

OR

You can edit template.php and add below code.

```
function yourtheme_preprocess_page(&$variables) {
     if (arg(0) == "checkout" && arg(2) == "complete" && is_numeric(arg(1))) {
        drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
        drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
      }

}

```
> 2 votes

# Answer
I'd probably just use JS Injector.

> Allows administrators to inject JS into the page output based on configurable rules. It's useful for adding simple JS tweaks without modifying a site's official theme - for example, a 'nighttime' color scheme could be added during certain hours. The JS is added using Drupal's standard drupal\_add\_js() function and respects page caching, etc.
> 0 votes

---
Tags: 7, rules
---


title: How do I search partial words?

text:
# Question
Title: How do I search partial words?
I'm working on a site with the Search API Solr module.

I notice that, in fulltext searches, the system gives results only for entire word. If I've a title like "Beautiful", if I search "eautiful" it doesn't find something. Is there a way to solve this?

# Answer
Set up Solr with the class EdgeNGramFilterFactory. This will not catch 'eautiful' instead of 'beautiful', but will give results on bea, beau, beaut and so on depending on minGramSize and maxGramSize. IMO this will be sufficient for most searches.
> 6 votes

# Answer
You could try adding 'beautiful' to the spelling suggestions for Solr. I believe there is a spellings.txt file in the Solr profile you are using for your site. It's probably in the apache-solr-1.4.1/example/solr/conf folder of your Solr installation. This is just from memory of setting this up several months ago, so the location could be wrong. The spelling suggestions will just notify the user that they may have misspelled a word and suggest what it thinks is the correct spelling. If you want to automatically search for the new spelling, you would probably have to write something yourself.

Some more details:

http://www.lucidimagination.com/blog/2010/08/31/getting-started-spell-checking-with-apache-lucene-and-solr/

http://wiki.apache.org/solr/SpellCheckComponent
> 2 votes

# Answer
Did you try fuzzy search project? It's maybe a good solution...If you write `beaut` he will match `beautiful`

As described in the documentation

> Each word in a node is split into 3 (default) letter lengths, so 'apple' gets indexed with 3 smaller strings 'app', 'ppl', 'ple'. The effect of this is that as long as your search matches X percentage (administerable in the admin settings) of the word the node will be pulled up in the results.

I think i will implement this module in one week on a server test because my actual boss wants some result even if there are some mispellings.
> 2 votes

---
Tags: 7, search
---


# Question
Title: How can I add extra data to a file field?
I am using Drupal 7's core module, file.

The file field array looks like this:

```
[field_game] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [fid] => 57
                        [display] => 1
                        [description] => the-pyro-guy.swf
                        [uid] => 0
                        [filename] => the-pyro-guy.swf
                        [uri] => public://swf/the-pyro-guy_2.swf
                        [filemime] => application/x-shockwave-flash
                        [filesize] => 5506729
                        [status] => 1
                        [timestamp] => 1346017444
                        [rdf_mapping] => Array
                            (
                            )
                    )
            )
    )

```

In addition to the above data, I want to store keys containing the game's height and width in this same file field. Can I do this, preferably in code?

# Answer
> 3 votes
You can't by default, but check out the File Entity module.

> This module extends the core file entity, making it a full fledged entity, allowing for fields, display formatters, and more.

This allows you to add fields (such as a height/width field) to files in the same way that you add fields any other fieldable entity (nodes, terms etc...).

# Answer
> 1 votes
You can't. Doing so goes against drupal design; drupal won't let you do that.

Instead, create a new field with the data you want, then group the two fields together using something like Fieldgroup

# Answer
> 0 votes
I am having good luck getting SWF dimensions automatically with PHP getimagesize

---
Tags: entities
---


# Question
Title: Fatal error: Unsupported operand types in field.info.inc
I'm cloning my client's drupal 7.15 site from online to my localhost. I received a copy of site folder and a copy of a sql dump file. I installed them into my localhost.

When I run the site, firstly I encountered the error:

> Fetal error: Class name must be a valid object or a string in C:\xampp\htdocs\mysite\includes\common.inc on line 7679

But the error went away when I did clear all cache tables manually via phpMyAdmin. Unfortunately, the next error appeared.

> Fatal error: Unsupported operand types in C:\xampp\htdocs\mysite\modules\field\field.info.inc on line 294

**\[Edit\]**
I installed Drush and navigated to my site in Drush command line, but I could not run commands except "drush" because of that error.

> C:\xampp\htdocs\mysite\>drush user-login
> Drush command terminated abnormally due to an unrecoverable error. \[error\]
>
> Error: Unsupported operand types in
> C:\xampp\htdocs\mysite\modules\field\field.info.inc, line 294
>
> C:\xampp\htdocs\mysite\>drush status
> Drush command terminated abnormally due to an unrecoverable error. \[error\]
>
> Error: Unsupported operand types in
> C:\xampp\htdocs\mysite\modules\field\field.info.inc, line 294
>
> C:\xampp\htdocs\mysite\>drush cache-clear
> Drush command terminated abnormally due to an unrecoverable error. \[error\]
>
> Error: Unsupported operand types in
> C:\xampp\htdocs\mysite\modules\field\field.info.inc, line 294

When I traced into **field.info.inc**, I found that `$instance['settings']` ( of the first parameter of \_field\_info\_prepare\_instance ) is missing for the field `field_tags`. Thus, the "+=" operation for arrays failed.

```
print $instance
Array
(
    [id] => 5
    [field_id] => 3
    [field_name] => field_tags
    [entity_type] => node
    [bundle] => article
    [deleted] => 0
)
print $instance["settings"]

****************
print field_info_instance_settings() call on taxonomy_term_reference
Array
(
    [user_register_form] =>
)

```

# Answer
> 1 votes
Your problems indicate that the copy did not come out right. Rather than try to diagnose the symptom, start over and copy the site again from scratch. If you can use Drush, perhaps Drush rebuild would help. You could also use the drush rsync and drush sql-sync commands directly.

---
Tags: 7, entities
---


# Question
Title: Can someone help me with contextual filters in profile2
I would like to single out a second profile with a views page using basic taxonomy reference or user information. Can you help me get my contextual filter to work with either user id, profile id, or taxonomy reference. I have my view to show users of a particular roll type. All users of this type will have a unique taxonomy reference ( or tag). When I choose fields for this tag in contextual filters and test it using the tag I don't get any results.

# Answer
> 0 votes
I was able to (finally) populate something on the user id. I guess it's the best way because I am going to be using rules to handle the information after the profile is created. Unfortunately, for some reason when I create a new user sometimes one of my profile id's is set to '0' *shrugs* which throws off the population of the field (check this especially if you use profile2\_regpath).

How I was able to do it was to like this

I referenced the profile based on user id... then I drew three relationships on the profile, the profile type, and the user id. I finally chose fields that substantiate the information I needed the user to see (in this case they are just testing it out). Please let me know if there is another way. I'm assuming there has to be something else out there or something I am missing. It populates one user at a time based on the profile owner's user id.

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


# Question
Title: I can't install views module. Error Memory or infinite loop
> **Possible Duplicate:**
> How do I avoid the error “out of memory”?

In my site, I can't install Views module. When I check it on admin/modules and then I press on save configuration I've got these error:

> **Fatal error**: Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in (...)/public\_html/includes/menu.inc on line 3714.

This is the code of menu.inc file:

```
3709  $item += array(
3711    'access arguments' => array(),
3712    'access callback' => '',
3713    'page arguments' => array(),
3714    'page callback' => '',
3715    'delivery callback' => '',
3716    'title arguments' => array(),
3717    'title callback' => 't',
3718    'theme arguments' => array(),
3719    'theme callback' => '',
3720    'description' => '',
3721    'position' => '',
3722    'context' => 0,
3723    'tab_parent' => '',
3724    'tab_root' => $path,
3725    'path' => $path,
3726    'file' => '',
3727    'file path' => '',
3728    'include file' => '',
3729  );

```

Problem with `'page callback' => '',` ??

It's like a infinite loop that crash, because 256 M for Drupal 7 it would be sufficient.

Actually the value of variable `memory_limit` of php.ini is 256M . I can't increase it because is a shared hosting, and 256M is the limit. I don't have access via SSH

I try to modificated this value in settings.php, but it's locked on 256 by hosting provider

`php_info` show this:

```
Directive        Local Value    Master Value
memory_limit     256M           256M

```

The list of installed non-core modules are:

* Administration menu
* Boost
* Chaos tools
* Libraries
* Pathauto
* Pathologic
* Redirect
* Smiley
* Sub-pathauto
* Tagadelic
* TagCanvas
* Token
* Transliteration
* XML sitemap

Thank for you reading. Grettings

# Answer
> 0 votes
There should not be any problem if there is 256M ram allocated. What i would suggest is clear your cache and install one module at a time. Like rather then installing the whole views list of module just install one by one. Another good option is to use drush to install modules but unfortunately you do not have ssh access.

---
Tags: installation
---


# Question
Title: How to do an embedded select (with count()) with the Drupal 7 database api?
Another day, another challenge with the Drupal 7 database API. I'm trying to do something like this:

```
select n.nid,
     (select count(*) as count
          from {node_cnt} nc where nc.nid = n.nid) as node_count
from {node} n

```

That is, I want to get back a set of node id's and the number of times that each id appears in the table node\_cnt. I'm going to be laying in some other conditions and pager stuff, so I think I need to do this with db\_select. This should be simple, I suppose, but I just haven't figured out the right way to think about this stuff yet. Any advice out there? Thanks!

# Answer
I don't think there's any existing method that will let you add a structured sub-query as an expression, so you're probably going to be left with something like this:

```
$query = db_select('node', 'n')
  ->fields('n', array('nid'));

$sub_query = '(select count(*) as count from node_cnt nc where nc.nid = n.nid)';
$query->addExpression($sub_query, 'node_count');

// Build the rest of the query.

```
> 2 votes

---
Tags: 7, database
---


title: POSTing a FormAPI form to another path?

text:
# Question
Title: POSTing a FormAPI form to another path?
I have a simple form, presenting an "Order this" button. That form is placed on a node. When people press that button, I want to start an ordering-workflow.

Currently the Drupal-way seems to be:

* Add form to node on `node/123`,
* User clicks form-submit, POST goes to `node/123`.
* `hook_form_submit()` gets fired, receives POSTed values trough form API.
* In that function, the POSTed-data is stored in a Session; then a drupal\_goto() sends redirect-header to `/shop/checkout`, user GETs `/shop/checkout`.
* Code building the `/shop/checkout` page must retrieve information from Session to build the checkout-workflow.

How can I simply send the POST to `/shop/checkout` and present my HTML there, based on the POST, instead of all the intermediate goto and session-spaggetti?

# Answer
The trick is to simply set `$form['#action']` to whatever URL you want to POST to.

Like this:

```
//....
$form = array(
  //..build the FAPI array
);
$form['#action'] = "shop/checkout";
return $form

```

In the place where you build the form. And the POST is sent to "shop/checkout".
> 0 votes

---
Tags: 7, redirection, forms
---


# Question
Title: struggling with template_preprocess in module
I know there is a lot of documentation on this function on google, but I am still not able to get this hook to run for my holidayautosxml\_carsearch\_form. Could anyone advise on what I am doing wrong.

The Theme function is running fine. If I put exit(); in that function I get white screen of death. However if I put exit(); in the template\_preprocess function nothing happens.

I have cleared all the caches.

my template is called holidayautosxml-carsearch.tpl.php and it is located in the module folder.

Here is my theme function

```
function holidayautosxml_theme(){
return array(
            'holidayautosxml_carsearch' => array(
                    'template'=>'holidayautosxml-carsearch',
                    'render element'=>'form',
            ),

    'halocationresults' => array(
        'template' => 'halocationresults',
        'variables' => array('haresults' => NULL,),
    ),
    'hapriceslist' => array(
        'template' => 'hapriceslist',
        'variables' => array('haprices' => NULL,),
    ),
);
}

```

Here is my template\_preprocess function

```
function template_preprocess_holidayautosxml_carsearch(&$variables){

$variables['holidayautosxml_carsearch'] = array();
$hidden = array();
//Provide variabels named after the form keys so themers can print each element independently.
foreach (element_children($variables['form']) as $key){
    $type = $variables['form'][$key]['#type'];
    if ($type == 'hidden' || $type == 'token'){
        $hidden[] = drupal_render($variables['form'][$key]);
    }
    else{
        $variables['holidayautosxml_carsearch'][$key] = drupal_render($variables['form'][$key]);
    }
}
//Hidden form elements have no value to Themers. no need for seperation.
$variables['holidayautosxml_carsearch']['hidden'] = implode($hidden);
//collect all form elementsto make it easier to print the whole form
$variables['holidayautosxml_carsearch'] = implode($variables['holidayautosxml_carsearch']);
}

```

and here is my form function

```
function holidayautosxml_carsearch_form($node, &$form_state){

    $country_list = _get_country_list();
    $form['country'] = array(
            '#type'=>'select',
            '#title'=>'Select Country',
            //'#description'=>'Select the country where you want to collect the car',
            '#options'=>$country_list,
            '#ajax' => array(
                'callback' => 'update_officename_autocomplete',
                'wrapper' => 'haofficename',
            ),
    );

    $citylist = _get_city_list($form_state['values']['country']);

$form['officename'] = array(
    '#type'=>'select',
    '#title'=> t('Location'),
    //'#description' => t('Select the location where you want to pick up the car'),
    '#required' => TRUE,
            '#options' => $citylist,
            '#width' => 50,
            //'#autocomplete_path'=>'location-autocomplete',
            '#prefix' => '<div id="haofficename">',
            '#suffix' => '</div>',
);

    if (!empty($form_state['values']['country'])){
        $form['officename']['#autocomplete_path'] = 'location-autocomplete/' . "{$form_state['values']['country']}";
    }
    $dateformat = 'd-m-Y H:i';
    $form['datefrom'] = array(
        '#required'=>TRUE,
        '#type'=>'date_popup',
        '#date_format'=>$dateformat,
        '#title'=>t("Pickup date"),
        //'#description'=>t("The date you are picking up the car"),

        );

    $form['dateto'] = array(
        '#required'=>TRUE,
        '#type'=>'date_popup',
        '#date_format'=>$dateformat,
        '#title'=>t("Dropoff date"),
        //'#description'=>t("The date you are bringing the car back"),
    );

$form['submit'] = array(
'#type'=>'submit',
'#value'=>'Search Now',
'#submit'=>array('holidayautosxml_carsearch_form_submit'),
);

return $form;
}

```

# Answer
> 0 votes
OK, I found the solution. The code I posted above only seems to work when I add, `$form['#theme'] = 'holidayautosxml_carsearch';` to the form specification.

Hope this helps someone.

Simon

# Answer
> 2 votes
I think it should be `holidayautosxml_preprocess_holidayautosxml_carsearch(&$variables)`. Basically the syntax is `[yourModuleName|yourThemeName]_preprocess_[themeFunctionName](&$variables)`.

Also you need to flush your cache after you make the change.

---
Tags: 7, forms, theming
---


title: recent content block with thumbnail?

text:
# Question
Title: recent content block with thumbnail?
I want to theme the Recent Content block with associated thumbnail of each node. After researching for a long time I found the function `node_get_recent()`. This function selects data from table 'node', but this table doesn't include any url pointing to the url of an image, which means I am not be able to use $node-\>(url of this thumbnail) to fetch its thumbnail. I happend to find the url of the thumbnail is located in the table 'file\_managed', but I still cannot associated it with table 'node' through leftjoin.

I do not know how to do it the right way. I do not want to use Views. Thanks!

---

When I put the following code into my .module file the title displayed for each node is the same.

```
function example_contents() {
  $number_of_post = 10;
  $result = db_query("select n.title,n.nid,f.entity_id,fm.fid,fm.uri from {node} n left join {field_data_field_image} f on n.nid=f.entity_id left join {file_managed} fm on f.field_image_fid=fm.fid   limit $number_of_post");
  $items = array();
  foreach ($result as $node) {
    $items[] = l($node -> title,'node/'.$node -> nid);
  }
  return array('#markup' => theme('item_list', array('items' => $items)));
}

```

`$node -> title` turned out to be same, however `$node -> nid` worked. That is to say the list of nodes used the same title but different urls. What was wrong with my code? Secondly, I do not know where to put my `$node -> uri` into `$items[]` in order to display the thumbnail.

# Answer
to slecet image uri you have to do

```
selest uri from node
join field_data_filed_image on field_data_filed_image.entity_id = node.nid
join file_managed on filed_image_fid = fid

```

anfd you can use this function to get thumbnail using uri

```
<img class="image" src="<?php print image_style_url('thumbnail', $block->uri) ?>"/>

```
> 0 votes

# Answer
Looking at the sql query I am assuming it is Drupal 7 so you can also use entity field query

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'node type')
      ->propertyCondition('status', 1);
$result = $query->execute();
$nodes = node_load_multiple(array_keys($result['node']));

```

After you get a list of nodes you can do a foreach loop over all the nodes and you will have the image field available in each node object.

Also for more documentation about field entity query and options please refer to http://drupal.org/node/1343708 http://api.drupal.org/api/drupal/includes!entity.inc/class/EntityFieldQuery/7
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Capture generated Drupal 7 html output into a variable
Trying to hook into Drupal 7 from an external php file by using various variants of ...

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
ob_start();
menu_execute_active_handler();
$contents = ob_get_clean();
return $contents;

```

However, it seems D7 just spits out the HTML to the browser on the `menu_execute_active_handler()` call.

Any ideas how to get the html output into my variable?

# Answer
Tracking the Drupal flow line by line and function by function reveals the culprit to be ob\_flush in the drupal\_page\_footer function

Using the following instead of ob\_flush would make the application a bit more friendly

```
$data = ob_get_contents();
ob_clean();
print $data;

```

---

Expanding on this,

Finally solved by adding a delivery callback to my module\_menu function and handling things there to bypass the problem function.

```
/**
 * Implements hook_menu().
 */
function MODULE-NAME_menu()
{
    $items = array();
    $items['MODULE-NAME'] = array(
        'page callback'     =>  'MODULE-NAME_output',
        'access arguments'  =>  array('access content'),
        'delivery callback' =>  'MODULE-NAME_deliver_html_page',
        'type'              =>  MENU_CALLBACK
    );

    return $items;
}

/**
 * Page callback: Display MODULE-NAME HTML Output
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_output()
{
    return 'Some Output HTML';
}

/**
 * Delivery callback: Render MODULE-NAME Page
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_deliver_html_page($page_callback_result) {
    /* Adapted from "drupal_deliver_html_page" */
    // Menu status constants are integers; page content is a string or array.
    if (is_int($page_callback_result))
    {
        // Integers mean an error page is required!
        // Send to the default Drupal function and exit.
        // Note use of exit instead of drupal_exit (not needed here).
        drupal_deliver_html_page($page_callback_result);
        exit;
    }
    elseif (isset($page_callback_result))
    {
        /* Print anything besides a menu constant if not NULL or undefined. */
        // Send the correct charset HTTP header if code running
        // for this page request has not already set the content type header.
        if (is_null(drupal_get_http_header('Content-Type')))
        {
            drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
        }
        // Send appropriate HTTP-Header for browsers and search engines.
        global $language;
        drupal_add_http_header('Content-Language', $language->language);
        // Render page
        print drupal_render_page($page_callback_result);
    }
    /* Adapted from "drupal_page_footer" */
    // Perform end-of-request tasks.
    global $user;
    module_invoke_all('exit');
    // Commit the user session, if needed.
    drupal_session_commit();
    if (variable_get('cache', 0) && ($cache = drupal_page_set_cache()))
    {
        drupal_serve_page_from_cache($cache);
    }
    else
    {
        $data = ob_get_contents();
        ob_clean();
        print $data;
    }
    _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
    drupal_cache_system_paths();
    module_implements_write_cache();
    system_run_automated_cron();
}

```
> 1 votes

---
Tags: 7, routes
---


# Question
Title: Fivestar multiple axis reviews and views
I want to have multiple axis comment reviews for nodes.
Example - rate a restaurant by the following criteria: food, drinks, atmosphere, location.

I want to order the nodes in a view according to the average vote.

**Questions:**

1. How can I setup the views relationship and fields to order nodes by total rating?
2. Should I create a separate vote tag in fivestar settings for each axis?
3. Is this possible out of the box with fivestar for D7?

---

**UPDATE**

To illustrate better the problem, here are the screenshots and exact numbers I'm getting.

Views settings
Views output
Calculations from reviews

---

**UPDATE 2**

Thanks to everyone who posted here.

I'm still not able to aggregate the votes correctly but I think it's due to some settings in views.

I will award the bounty and post the code/solution I used as soon as I solve it completely. I think Ayesh and junedkazi gave the correct answer saying almost the same thing. Will confirm when I solve it completely.

---

**FINAL UPDATE**

The votes are not aggregated on the nodes properly. Custom module is calculating the "overall" value for each comment and that works as it should. But when the fivestar/votingapi calculates the votes for parent node on node view page and on views listing page, it does not work. It takes into consideration only the *last* review, and not the rest.

Just in case, here's the calculating code I'm using in a custom module:

```
/**
 * Implements hook_comment_presave().
 */
function MYMODULE_comment_presave($comment) {
  // Keep these as separate variables so the code doesn't have to be
  // updated if the number of axis has been changed from admin.
  $axis_count = 0;
  $rating_sum = 0;
  // Go through all elements and check if this is a rating field.
  // Avoid hardcoding the field names (except the overall field).
  foreach ($comment as $element_id => $element) {
    if (is_array($element) && isset($element[LANGUAGE_NONE][0]['rating'])) {
      $rating_sum += $element[LANGUAGE_NONE][0]['rating'];
      $axis_count++;
    }
  }
  // Trim out eventual weird decimals
  $overall = number_format($rating_sum / $axis_count, 0);
  // Save the value in the overall field
  $comment->field_overall[LANGUAGE_NONE][0]['rating'] = $overall;
}

```

Please if anyone has any ideas I'd be really thankful. Even though the bounty expired, I will award it for a working solution (I don't care about the points).

# Answer
> 2 votes
**Fivestar Widget**

I believe the Fivestar widget stores values as a percent average rather than as a vote average. In otherwords the Fivestar widget is storing a value between 0-100 rather than 0-5.

When you have a Fivestar widget collecting 0 to 5 stars, each star is worth 20. This is why when you have an average of '2 stars', your seeing a value of 40. (2\*20=40)

To extend this:

* A node with 1, 2 star vote will be stored as 40
* A node with 2, 2 star votes will be stored as 40
* A node with 1, 2 star vote and 1, 3 star vote will be stored as 50

---

This can easily be fixed by dividing the displayed output by 20.

From there, I believe your view may already be setup properly.

I'll rework my answer if this isn't relevant here.

# Answer
> 2 votes
I had a similar use case but instead of using comments I created a separate node type called as review.

I created multiple axis using the fivestar settings. Also an average vote axis to store the average.

After this I created each axis on the node type which is "Stars (rated while viewing)" and making sure the exposed check box is checked off on the display settings.

After this I re-used the same fields on the review type (in your case it will be the comment) and set the widget type as "Stars (rated while editing)" and select the proper parent reference.

Also I had field permissions module installed and with proper permissions to hide the avg vote axis from normal user on the review content type. You can do it with `hook_form_alter` as well.

Then I added this small piece of code to calculate the avg vote based on all the other axis. In your case it will be hook\_comment\_presave.

In this case I am assuming you have the entity api module bcoz I am using `entity_metadata_wrapper` function.

```
function hook_node_presave($node) {
  if ($node->type == 'review') {
    // get all fivestar fields
    $fields = field_read_fields(array('type' => 'fivestar'));
    // load the wrapper with node information
    $wrapper = entity_metadata_wrapper('node', $node);
    // to hold each axis vote
    $total = array();
    foreach ($fields as $field_name => $field) {
      // make sure your field belongs to the same bundle and is not deleted
      // and is not the avg vote field
      if (($fivestar_field = field_read_instance('node', $field_name, $node->type)) && (!$fivestar_field['deleted']) && ($fivestar_field['field_name'] != 'field_average_rating')) {
        // Get the axis value
        $value = $wrapper->$field_name->value();
        // place the value in the total array
        $total[] = $value;
      }
    }
    $node->field_average_rating[LANGUAGE_NONE][0]['rating'] = array_sum($total)/count($fields);
  }
}

```

# Answer
> 1 votes
***How can I setup the views relationship and fields to order nodes by total rating?***

You need to add a relationship to vote results and define the tag. (see #2).

***Should I create a separate vote tag in fivestar settings for each axis?***

YES!

***Is this possible out of the box with fivestar for D7?***

Not out-of-the-box, if you want to have an automagically calculated overall field. even though there are discussions about Computed Field module, I had to invest time on a custom module (that uses hook\_comment\_presave to calculate overall voting).

The main concept behind multi-axis voting is, tags. First, you need to add multiple tags in Voting API settings page. It defaults to "vote" but you will need food, drinks, atmosphere, location and probably an overall. Note that overall calculations could be a little tough unless you make a module to do so.

First, add 4 fields to the **comment form** under 4 different tags (or 5, if you want an overall one. if you want to calculate overall from other 4 fields, lets do so later).

Each field can be used (rated) on editing (while leaving the comment). Rating target, parent node. **But** individual vote values are still stored in the comment field. So when you display the comment, you will see individual comment's rating data.

Then, the tricky part. **You need to add 4 (or 5, for overall) fields to the node as well**. Choose this under each tag you created earlier. Now you will be able to see aggregated results in normal node View. For Views, you need to define the tag.So without an extra overall tag, you will only be able to sort nodes by best food restaurants by votes, likewise.

You can however have a hidden overall field in comment form and then calculate the overall value from other 4 axises on a hook\_comment\_presave. I'm assuming you will be able to do it yourself. I have a working module if you want to inspire. (it's for a client though).

---
Tags: 7, views, rating
---


# Question
Title: How to make custom end user text in a form available for editing for a e.g. editor role?
Within a form build in a custom module trough the form api I'm using pieces of text (eula, help, hints) of which some of them need to be editable by my client (editor role).

For example:

```
$form['eula'] = array(
  '#type' => 'radios',
  '#title' => t('This text need to be editable. I agree to be bound by bla bla bla.'),
  '#options' => array('Ja'=>'Ja / Yes'),
  '#required' => TRUE,
);

```

I want to facilitate a central point where those text strings (like #title) can be edited and a way I can retrieve them in this custom module.

What's best practice for this scenario to do so? Create a content type for this or perhaps use variable\_set/get?

Basically I want one location where my client can edit all those text strings. To use a content type for this and node\_load() everytime feels a bit too much.

Thanks in advance

# Answer
> 2 votes
As long as the string or text is passed via t() function you can override it using String Overrides module. Here is a quote from module's project page:

> Provides a quick and easy way to replace any text on the site.

**UPDATE**

You can also use Variable module. Quote from project page:

> ... provides a registry for meta-data about Drupal variables and some extended Variable API and administration interface.
>
> This is an API module so it must be installed only when other modules require it.

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


# Question
Title: menu_tree_all_data returning empty arrays for custom menus
I have tried to get the menu tree for two different custom menus using menu\_tree\_all\_data, but they have returned empty arrays, while using it to get 'navigation' menu works.

Does anyone have any idea about what might be going on?

# Answer
If you are looking to print a menu tree, then it's answered here. I have tried this and solution worked !

```
<?php

$tree = menu_tree_page_data('menu-name'); // Replace menu-name with menu name you want to print
$first_level = db_query("SELECT mlid FROM {menu_links} where menu_name = 'menu-name' and plid = 0 ORDER BY weight ASC");
while ($item = db_fetch_object($first_level)) {
  $mlid = $item->mlid;
  // Extract subtree
  $subtree = admin_console_menu_get_subtree($tree, $mlid);
  // Render as HTML menu list
  $content .= menu_tree_output($subtree);
}
return $content;
?>

/**
* Extract a specific subtree from a menu tree based on a menu link id (mlid)
*
* @param array $tree
* A menu tree data structure as returned by menu_tree_all_data() or menu_tree_page_data()
* @param int $mlid
* The menu link id of the menu entry for which to return the subtree
* @return array
* The found subtree, or NULL if no entry matched the mlid
*/

function admin_console_menu_get_subtree($tree, $mlid) {
  // Check all top level entries
  foreach ($tree as $key => $element) {
    // Is this the entry we are looking for?
    if ($mlid == $element['link']['mlid']) {
      // Yes, return while keeping the key
      return array($key => $element);
    }
    else {
    // No, recurse to children, if any
      if ($element['below']) {
        $submatch = admin_console_menu_get_subtree($element['below'], $mlid);
        // Found wanted entry within the children?
        if ($submatch) {
          // Yes, return it and stop looking any further
          return $submatch;
        }
      }
   }
}
// No match at all
return NULL;
}

```
> 2 votes

# Answer
Drupal adds 'menu-' to the menu name you specify, but doesn't use this on stock menus, so 'primary-links' works for the Primary Links menu.
> 1 votes

---
Tags: 6, routes
---


# Question
Title: Add extension .csv to file created with Views Data Export
To export user data into a csv I've setup a view display of type **data export** succesfully. I've setup a path "admin/people/export" and when visiting it will return a file. The file is a csv file but it's created without the extension .csv.

Is there a way to create this file with this extension?

Thanks in advance

# Answer
In the view settings click on *Format: CSV File \> Settings*

>

In the dialog box that appear, be sure that *Provide as file* is selected. In the *Filename* field that appears when that option is selected, leave the default value (*%view.csv*).

>

*%view*, which adds the view machine name to the filename, is only one of the available replacement tokens. As visible in the screenshot, the other ones are:

* %display
* %exposed
* %timestamp-full
* %timestamp-yy
* %timestamp-yyyy
* %timestamp-mm
* %timestamp-mmm
* %timestamp-dd
* %timestamp-ddd
* %timestamp-hh
* %timestamp-ii
* %timestamp-ss
> 9 votes

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


title: Why hook_user_logout is not working?

text:
# Question
Title: Why hook_user_logout is not working?
I am trying to display message or run some other action when user logout and redirect them to home page. I am trying following code, but all I get is just set\_message and it never logoff me. why?

```
/**
 * Implements hook_user_logout().
 *
 */
function ucenter_user_logout($account) {
  drupal_set_message(t('Thanks for visiting, come again!'));
  drupal_goto();
}

```

# Answer
> 5 votes
Calling `drupal_goto()`, you are avoiding the session is destroyed. The function that invokes `hook_user_logout()` (user\_logout()) contains the following code.

```
  watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
  module_invoke_all('user_logout', $user);

  // Destroy the current session, and reset $user to the anonymous user.
  session_destroy();

  drupal_goto();

```

drupal\_goto() calls drupal\_exit(), which means that with your Drupal's execution is interrupted before `session_destroy()` is called.

What you can do is changing the code to something similar to the following one.

```
function ucenter_user_logout($account) {
  user_cookie_save(array('ucenter.logoff' => '1'));
}

function ucenter_init() {
  // Check the value of the cookie Drupal_visitor_ucenter_logoff
  // and print the message if the user precedently logged off.
}

```

---
Tags: 7
---


title: Linking content types

text:
# Question
Title: Linking content types
I need to link content from one content type to another automatically so that when one of the type is updated with new content, the other gets filled automatically. Any ideas?

# Answer
> 1 votes
You need to use Entity Reference module to connect two different content types content. Add a field Entity Reference in one content type and reference it to another content type.

To auto update another content type content, you need to use hook\_node\_insert and hook\_node\_update on first content type, and get referenced nid and update second content type content using node\_save.

---
Tags: nodes
---


title: Displaying content in different ways

text:
# Question
Title: Displaying content in different ways
I sort of ran into a problem here, for a new project a piece of the homepage can have different layouts.

For example:

```
-----------------
| N  |    C     |
| E  |    O     |
| W  |    N     |
| S  |    T     |
|    |    E     |
|    |    N     |
|    |    T     |
-----------------

```

or

```
-----------------
|       C       |
|       O       |
|       N       |
|       T       |
|       E       |
|       N       |
|       T       |
-----------------

```

or

```
-----------------
|               |
|     NEWS      |
|               |
-----------------

```

So there are 3 types of layouts, news + content, just content and just news. What would be the best way to do this? Currently I'm using Panels to build the homepage, this is just a small part of it.

It also would have to be very convenient for the user to switch styles, any ideas for this?

# Answer
Sorry, I kind of lost track of this issue.

What I ended up doing was using an extra custom field as a class selector, that way I was able to use javascript to show or adjust different part of the content.
> 0 votes

# Answer
1. You can use Panels, Display Suite and Context to build a different layout flexible and custom layout in your theme.
2. You can also build a custom theme with there layouts and switch the layout home page based on context. If you are planning for theme, you can write a subtheme for Omega, a HTML5 base theme, or can you choose the best base theme as per your need.
> 0 votes

# Answer
Homebox module allows you to manage the layout which you show in the Graphics. This is also implemented in Drupal's official website. In this users can also have choice to disable/enable blocks.

So you can create two blocks:

News and Content. Add this blocks to homebox.
> 0 votes

---
Tags: views, panels, theming
---


# Question
Title: After using unset($form['author']); for comment module drupal returns errors
As I would like to allow users print their names with comments I added a new field called comment\_name. To not have 2 fileds with name I used the code to unset filed "name" from comment.module

```
function user_add_node_form_comment_form_alter(&$form, &$form_state) {
unset($form['author']);
return $form;
}

```

But after adding a comment I receive an error message

```
Notice: Undefined index: name in function comment_form_validate() (line 2127 in file D:\sites\theme\www\modules\comment\comment.module).
Notice: Undefined index: mail in function comment_form_validate() (line 2140 in file D:\sites\theme\www\modules\comment\comment.module).
Notice: Undefined index: homepage in function comment_form_validate() (line 2143 in file D:\sites\theme\www\modules\comment\comment.module).

```

I guess it because I unset a form that has to validate if user logged in or not but don't know how to solve it.

P.S. Also I use the Ajax Comments Module

# Answer
> 5 votes
You should try this if you just want to hide the comment default name field !

```
function user_add_node_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['name']['#access'] = FALSE;
}

```

---
Tags: 7, forms, comments
---


# Question
Title: Uncaught TypeError jquery function is not read anymore
I've on a Drupal 6 site which run since 2 years, a new problem at first with CloudZoom but i start to think that it's a little more than that.

I've errors in the firebug console which says : Uncaught TypeError: Object function ... has no method 'cookie' or Uncaught TypeError: Object function ... has no method 'cloudzoom'

So Cloudzoom don't works anymore on some language... what is strange is that it still work in english.

I've take a look at the code and it's ok, it worked in the past ans still work in english. I also make sure that JS file are call in the right order jquery\>librairies\>myOwnJs.

what i need is to understand the error message "Uncaught TypeError: Object function" : what can generate that kind of error, where to search. I spend a lot of time on that and don't really know where to look now.

# Answer
> 1 votes
You got it - basically it means the function isn't defined or is conflicting. You have to load the jQuery file that you're going to use and not multiple or you'll get that type of strange behavior.

The workaround I've used, which does work -- assuming you're not using that particular function -- is to define the function yourself as an empty function and it'll reference that and just keep on going. This came up in the Adobe Edge beta as fnCycle() was giving the same error. After putting the empty function in my own .tpl.php is solved and didn't kill the js execution.

Note though that while this may work for that one situation, you will have others if you leave conflicting versions of jQuery in there.

---
Tags: javascript
---


# Question
Title: Do I need to use a block or form to implement login box, or can I just post to a 'login' url the user details?
I have static HTML for a login box which contains a form with username and password inputs and is part of the site header, which will be on every page ie. this is not a login 'page'.

To integrate this with the Drupal login system, can I point the form action at a certain url to post the login details and perform the login? Thereby, not requiring any Drupal backend form/block/theme coding?

Or do I need to implement my own form, or customise an existing form to achieve this? If so, why is that? What do I need from the Drupal back end to successfully login ie. hidden form fields that need to be passed with the login details etc?

I am trying to implement the site in the cleanest way possible, using my own HTML 5/ CSS 3 markup, so overriding most html so that the tonne of classes Drupal adds, and the extra unnecessary markup are scraped. So, ideally I would like to avoid having to make a login form/block as part of the back end.

# Answer
> 0 votes
You can print login block in the tpl file. No need to use username/password fields of HTML/CSS.

```
<?php print drupal_get_form('user_login_block'); ?>

```

For Registration :

```
<?php print drupal_get_form('user_register_form'); ?>

```

# Answer
> 0 votes
You can theme your login form using **hook\_theme** in your **template.php**

```
function THEMENAME_theme(){
  return array(
  'user_login_block' => array(
      'arguments' => array('form' => NULL),
      'template' => 'user-login-block',
    ),
}

```

now create **user-login-block.tpl.php** in your theme. You can use your html and drupal\_render($form\[ELEMENTS\]) in that tpl file.

**For example**

```
<ul>
      <li>
        <label>Username</label>
        <span class="login_field_box">
        <?php
           $form['name']['#description']='';
           print drupal_render($form['name']);
        ?>
        </span>
      </li>
      <li>
        <label>Password</label>
        <span class="login_field_box">
        <?php print drupal_render($form['pass']);?>
        </span>
      </li>
      <li>
        <?php
            $form['submit']['#attributes']['class']=array('Login');
            print drupal_render($form['submit']);
        ?>
      </li>
    </ul>

    <div style="display:none"><?php echo drupal_render($form) ?></div> <!--this must be in your tpl at end-->

```

---
Tags: 6, users
---


title: Changing automatic URL alias

text:
# Question
Title: Changing automatic URL alias
I am populating a new site with my old site's content (i.e copying it) and wanted to make sure all the URLs will be the same. At the momement my old path is name.com/work/sony-folklore and and the new one is: name.building-site.com/content/sony.

NOTE: *name.com and name.building-site.com are dummy names that refer to the live and the development version of the site.*

What can I change to make the CMS generate the same URLs as they did in the old site?

Thanks

# Answer
> 1 votes
You can set the alias by editing a content. See the screenshot below to edit url alias.

---
Tags: nodes, uri
---


# Question
Title: How to use Drupal unixtime instead of timestamp
What is the proper Drupal way to deal with timestamp fields?

I wanted to create two timestamp fields in a MySQL table, but ran into some problems that I can't solve (see this question). So now I want to try it with the INT fields and Unix timestamps that Drupal uses.

The two columns in question are for "created" and "updated" purposes. What is the Drupal way to store a record with the current (UTC) time and how can I retrieve those timestamps in the user's own timezone? My server is on UTC time and I'm using Drupal 7.

# Answer
> 0 votes
Use REQUEST\_TIME.

I think that as long as you use Drupal to display/calculate the time, you shouldn't be worrying about time differences between the users or the site.

---
Tags: 7, database, datetime
---


# Question
Title: Halt registration when certain conditions are (not) met
On registration we have to look up the user-information in a remote database (JSON service), when user is not found there, or when some other error occurs, we want to halt the registration completely.

```
function foo_user_presave(&$edit, $account, $category) {
  $foo_bar = new FooBarSource($edit["foo_bar_invite_code"]);
  if ($foo_bar->is_valid()) {
    drupal_set_message(t('Fail'), 'error');
    //What now?
  }
}

```

Problem is that I fear some records are being written already in, or before hook\_user\_presave. From the documentation:

> A user account is about to be created or updated.

Is it safe to simply do a `drupal_goto()` to halt the registration? Would that cause orphaned records in the Database? What about other modules implementing this hook: would they break or be confused?

Is this hook the proper hook to determine if a user can register?

# Answer
> 5 votes
Do hook\_form\_alter for user registration form, and add extra validation function to the form using #validate like below.

```
$form['#validate'][] = 'extra_user_validation';

```

in function extra\_user\_validation set error after validation. So, that you can avoid the submit process and invoking hooks.

```
function extra_user_validation($form, &$form_state) {
   // Get the input values of registration form from $form_state['values']
   // Do validation & set error
}

```

That should work !

---
Tags: users
---


title: Make certain nodes of group Private

text:
# Question
Title: Make certain nodes of group Private
How can i make certain nodes of group Private in a Public Group irrespective of content types. So lets say I have a Public group X which has Page as a content type. So i have 10 as contents of groups which is public.So I have to make 2 contents of the group Private such that it is only available to the group members.

Tks in adv, -Vil

# Answer
Enable Group Content Visibility field on Content Type. Using that field you can mark content under a group as public or private.

You need to enable OG ACCESS module to see those fields in admin/config/group/fields

Select the bundle as your content type in node section and select field Group Content Visibility from Fields Dropdown, click on Add field to add Group Content Visibility field for Content Type.
> 0 votes

---
Tags: organic-groups
---


# Question
Title: Views 3: how to list users related to nodes category and exposed filter by that category
I need to list the node authors based on node category and also expose filter with that category. Can any one tell me how to solve this issue?

# Answer
> 0 votes
Follow below steps to solve the issue.

* Add relationship node author.
* In View Fields add field Node Author Name
* Add filter Node Category Field that is used to Categorize content.
* Expose the above filter
* Select Group By Node Author Name in View Style Settings so that you can see DISTINCT users belongs to Node Category

That should work i hope !

---
Tags: views
---


title: Adding Ajax to Book navigation block

text:
# Question
Title: Adding Ajax to Book navigation block
I am using book navigation block which contains links to content of BOOK.I would like add ajax functionality to this links.

I tried adding use-ajax class to this links.But i was unsuccessful.

Please let me know how to ajaxify links of book navigation block

Thanks a lot for the help.

# Answer
> 1 votes
If you are using drupal6(you haven't specified) then try the AdvancedBookBlocks module. It is built on the ideas of the jquery menu module and could help you.

If you are on drupal7 there is a port of the drupal 6 module though still a sandbox project. I have tried it out and it works. You can find it here

---
Tags: 7, ajax
---


# Question
Title: custom "register" button on a form - problem with redirection
How to make a custom register button in the user login form (block) so that it redirects to 'user/register' ?

Currently, when I click my custom "Register" button, the code in \_mymodule\_register is executed (I debugged), but the page just reloads, it does not go to user/register. I tried both drupal\_goto and form redirect, but nothing works.

```
function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('_mymodule_register'),
    '#limit_validation_errors' => array(),
  );
}

function _mymodule_register($form, $form_state) {
  $form_state['redirect'] = 'user/register';
  //drupal_goto('user/register');
}

```

# Answer
Use below code to achieve the same functionality.

```
function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#markup' => l('Register', 'user/register'),
  );
}

```

Theme it using css to look like a button. Done !
> 1 votes

---
Tags: 7, redirection, forms
---


# Question
Title: Entity Wrapper : how to delete multiple values field?
I have a multiple values field on the `user` entity. This field is `field_data`.

There are several values in this field. I want to delete all of them.

I tried the following code:

```
for ($i = 0; $i < count($user->field_data->value()); $i++) {
    $user->field_data[$i]->delete();
}

```

But I get errors about `->delete()` not being a method on this object. I also tried with `->clear()` to no avail.

I've been looking for examples on Google for how to do this, but my Google-fu is not so strong today.

# Answer
> 3 votes
Well, I solved it. The answer is kind of tricky.

You can't delete a value in a multiple values field. However, you can set it to "empty". When it's empty, it's removed.

Here is the code to use:

```
// Also, note the ->count() method
for ($i = 0; $i < $user->field_data->count(); $i++) {
  $user->field_data[$i]->set();
}

```

This way, values are now empty and the multiple fields have no value left. It's well shown in the UI too and the deltas are correctly handled in the database.

---
Tags: entities
---


# Question
Title: How do I add a title attribute to the search submit button, exposed search, and reset buttons?
I want to add the title attribute to the search submit button, the exposed filter search, and the reset button.

How can I achieve this?

# Answer
I have found the answer of my question.

I have used the following code in my form\_alter function.

```
if ($form_id == 'search_block_form') {
   $form['actions']['submit']['#attributes']['title'] = t('Search');
  }
  if ($form_id == 'search_form') {
   $form['advanced']['submit']['#attributes']['title'] = t('Search');
  }
  if($form_id == 'views_exposed_form') {
    $form['submit']['#attributes']['title'] = t('Search');
   $form['reset']['#attributes']['title'] = t('Reset');
  }
  return $form;

```

It solved my problem.
> 2 votes

---
Tags: 7, views, tooltips
---


title: Can't get AJAX on file upload working

text:
# Question
Title: Can't get AJAX on file upload working
I have a `managed_file` form element. I want to trigger an AJAX callback when a user clicks the upload button. But I can't seem to get anything working by attaching the `#ajax` element to the `managed_file` element. I know the `managed_file` element creates an upload button automatically, so I tried to hook into that using `hook_form_alter` but the button doesn't seem to have been created yet, so I can't attach the AJAX handler.

Any ideas?

# Answer
No, unfortunately, you can't use #ajax because managed\_file uses it internally for its own purposes.
> 3 votes

---
Tags: forms, ajax, files
---


# Question
Title: Node limit - based on cck field of referenced content type
I have 2 content types:

* Organisation (Name, address, tel, places)
* Internship (Reference to Organisation , Student, Mentor, ...)

Now for example I have an organisation with 2 places for students. So when this organisation is selected as a refernce in Internship node creation, it must check for the available places. If the pace is available then it needs to save the node else it should give an error message.

I have tried node limit module but it is not a solution.

Thanks.

# Answer
> 0 votes
My point of view this can be done at node submission time

**Alter the access callback for the menu callback:**

```
function custom_module_menu_alter(&$items){
    $items['node/add/internship']['access callback'] = 'my_custom_access_callback'
    // Next line needed for Drupal 7
    unset($items['node/add/review-sites']['access arguments']);
}

```

**Add a function as your custom access callback:**

```
function my_custom_access_callback() {
   global $user;

   /*Now check the selected organization which you are selecting from dropdown of entity reference and call it as $no_of_places. Also check the existing internship with same referenced organization and call it as $occupied_seats*/

   if ($no_of_places > $occupied_seats && user_access("create internship")) {
     return TRUE;
   }
   else{
     drupal_set_message('Print message about exceeded limit and/or user permissions.');
     return FALSE;
   }
}

```

---
Tags: nodes, entities
---


# Question
Title: Speed difference between db_select and EntityFieldQuery
Is there any performance difference between db\_select and EntityFieldQuery?

I would like to re-write portions of the site removing db\_select in favour of using EntityFieldQuery.

I hope that i will able to replace few db\_select calls with one EntityFieldQuery call, also.

# Answer
> 7 votes
There might be a slight difference in performance but I guess it depends on your implementation. As you said yourself: it might be possible to replace a couple of db\_select queries with EntityFieldQuery, although I can't really think of a situation where you'd be able to do that, if your db\_selects are solid.

If I'm not mistaken EntityFieldQuery actually uses db\_select or at least a SelectQuery to fetch data. I also think EntityFieldQuery looks up information about the entity that needs to be queried (ie: base table), this is cached though.

My guess is EntityFieldQuery would be somewhat slower, but the only way to see if you're losing any performance is by benchmarking (timing) it.

All in all I wouldn't worry about the performance of EntityFieldQuery. The biggest advantage of EntityFieldQuery is that it adds another layer of abstraction, making your code more loosely coupled and more cohesive. It's also pluggable so somebody could change the backend without you having to change any of your code.

---
Tags: database
---


# Question
Title: Views Content: Title as an autocomplete exposed filter?
I would like to provide an **autocomplete widget** for the `Content: Title` in a view (created by Views), in which this field is an exposed filter. By default, it's a **simple textfield**.

What's the best solution for this?

# Answer
You can use the Views autocomplete filter

It will work for node titles and other exposed text fields
> 3 votes

# Answer
I have used the Finder module, but it's too difficult to configure and use. It provides AJAX functionality to return results as a select option while typing. The Finder module is more of a field with auto-complete results.

I would suggest you use the Views Autocomplete Filters module which looks more applicable to your problem.
> 3 votes

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


# Question
Title: What's overriding my local_settings.php?
I'm using a local\_settings.php file, that includes several $conf settings. All of the settings were working as expected until just recently when the mail\_system setting started getting overridden somehow.

Now, if I run `$ grep mail_system local_settings.php -A2`, I get:

```
$conf['mail_system'] = array(
  'default-system' => 'DevelMailLog',
);

```

...yet, the output of `$ drush vget mail_system` is:

```
mail_system: Array
(
    [default-system] => DefaultMailSystem
)

```

I've always assumed that whatever was defined in the settings.php (or in this case the local\_settings.php) would trump the same variable defined elsewhere. I've checked all the other variables I'm setting inside the $conf variable in the local\_settings.php and they're set as they are in the file.

Where else might mail\_system be getting set that would override the $conf definition?

# Answer
> 1 votes
Enabling the Devel module fixed the issue. Ultimately, I think the issue is specific to the Mail System module and the unusual way it handles settings and defaults.

---
Tags: configuration
---


# Question
Title: Change the sorting order used for Book nodes
How can I change the order used for Book nodes, which by default is based on weight and title?

I have a set of nodes displayed inside a page that use a structured book. I want to display them ordered by weight and random, instead of weight and name.

The book is used to structure different types of local companies and restaurants.

I have traced the code looking for a solution, but it's a bit messy for me.

Is there a hook that could be helpful to achieve this?

# Answer
You should checkout the Book helper module.

> The Book helper module enables additional features from Drupal's menu system to improve the ordering of a book's pages. This module also allows administrators to further customize a book's navigation block.
>
> ### Features
>
> * Enhances the book outline manager
> * Adds 'enable' checkbox (aka hidden) to the manage book outline page
> * Adds an 'Order' tab (node/%/order) to a book's main page
> * Adds 'administer own book outlines' permission for ordering books from a book's main page
> * Removes the 'Outline' tab from all nodes
> * Removes the book fieldset from node edit pages if the content type does not allowed book outlines
> * Removes 'add child page' and 'printer-friendly version'
> * Removes book navigation
> * Customizes visibility of a book's navigation elements
> * Automatically 'Create new book' for selected content types
> * Includes 'Book (inline) navigation' block that can be easily positioned after a node's content
> * Disables new revisions from being created when a book's node title is updated
> * Displays a warning when deleting a book page (node/%/delete) that has child pages
> 0 votes

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


# Question
Title: Where does drush store the different module versions for a multisite installation?
I wonder where the different module versions are kept on a multisite installation.

Before I (re)discovered drush, I had several more sites sharing the core code and sites/all/modules a symlink to a common modules dir.

On upgrading core I set that link in the new sites/all dir.

And then I started using drush. So when I do drush up in the sites/my1stsite dir and it updates the modules, how can the other my2ndsite still have the old modules? (and be able to drush up-date itself?)

# Answer
If you are using a multisite installation with shared modules stored in sites/all/modules, then Drush pm-update will also put the new modules in this same shared directory. This means that you must also run updatedb on all of the other sites that share the same module code, as all of the sites will need to be upgraded at the same time.

It is far more convenient to use a single-site installation, and give every site their own complete copy of Drupal core + contrib modules, as you will then be able to update each site independently. Fortunately, splitting up a multisite install is as easy as cloning your Drupal files, and changing your web server virtual hosts configuration file to point at the new site's location.
> 1 votes

---
Tags: drush, updating
---


title: Can Drush update custom modules?

text:
# Question
Title: Can Drush update custom modules?
I'm currently using Drush Make to pull custom modules, installation profile, and various other modules/libraries when I provision a new Drupal site.

What I'd love is if I could use drush upc to update my custom modules. I'm not sure if this is possible if I provide some magic meta data to drush or include my .git with a specified remote host.

My understanding is that Drush leverages the update status module in core for this functionality so this may not necessarily be a Drush specific issue.

Any help or suggestions on where to look would be appreciated.

# Answer
> 3 votes
As you said, Drush relies on the update status module of Drupal to find code updates. If you wanted to use this mechanism for your own custom modules, you would have to make a server that had clones of the d.o modules you used, since pm-updatecode works with a single update server, and also has the same xml data structure for the releases of your custom modules.

There are two easier solutions:

1. Publish your custom modules on drupal.org - very easy, and a great option if your modules can be shared openly.
2. Just check out your custom modules from git; after running pm-updatecode, iterate over each custom module and do a 'git pull'.

The later could be integrated with drush pm-updatecode, either as a post-updatecode hook or as a feature request submitted in the Drush issue queue (patches welcome).

---
Tags: drush, updating
---


title: Get a list of all the blocks

text:
# Question
Title: Get a list of all the blocks
I need an array of all blocks in the site

For example, if I display the array, it should output the block info or block titles e.g Search, User etc

# Answer
Try this piece of code from a similar question

```
global $theme;
$all_regions = system_region_list($theme);
$blocks = array();
foreach (array_keys($all_regions) as $region) {
  $blocks += block_list($region);
}

```
> 1 votes

# Answer
Have a look at how blocks are defined. There are numerous hooks that are involved in providing a block. Call the appropriate one using module\_invoke\_all() to gather the appropriate information about the blocks.
> 0 votes

---
Tags: blocks
---


# Question
Title: Javascript hotel price/availability calendar
I'm trying to create a Javascript calendar which will show the price and availability of hotel rooms by date. Similar to this example (see Availability tab), however mine needs to show prices and availability for three different room types on each date.

So far I've tried out the Availability Calendars and Rooms modules, but both would require significant work to adapt to my needs.

I've also been looking into using a straight-forward calendar module. First I tried Calendar, however this reloads the page when moving to the next/previous month which won't do. Then I tried Fullcalendar, but I can't figure out how to make multi-day items appear as separate daily items (they appear as one item spanning many days), and there's also a problem rendering the calendar on a quicktab (it only shows the next/previous buttons and not the calendar until you actually click next or previous).

So I'm looking for some ideas on how to proceed...

PS I'm using Drupal 7.15

# Answer
I figured it out using the standard Calendar plugin. You need to create the view as normal, then I created a custom block which embeds the view 6 times, calling it with a different month argument each time. Then I added some javascript magic to hide and show the calendars as required.

**Create the block - PHP**

```
/**
 * Implements hook_block_info().
  */
function viajes_block_info() {
  $blocks['viajes_room_prices'] = array(
    'info' => t('Viajes: Room prices and availability calendar'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/*
 * Implement hook_block_view()
 * Display the search form in a block
 */
function viajes_block_view($delta = '') {
   $block = array();

switch ($delta) {
    case 'viajes_room_prices':
        $block['subject'] = t('Disponibilidad de habitaciones');
                    $block['content'] = viajes_room_prices();
                    break;
    }

    return $block;
}

function viajes_room_prices() {
$MONTHS_TO_SHOW = 6;
$hotel_nid = arg(1);

//js is already added by the reservation form code, no need to add it again
//drupal_add_js(drupal_get_path('module', 'viajes') . '/js/hotels.js');
drupal_add_js(array('viajes_room_price' => array('max_months' => $MONTHS_TO_SHOW)), 'setting');

//previous/next controls
$ret =
'<div id="viajes-rooms-controls">
    <div id="viajes-rooms-previous" class="disabled"><a>' . t('Previous') . '</a></div>
    <div id="viajes-rooms-next"><a>' . t('Next') . '</a></div>
</div>';

//calendars
for ($i=0; $i<=$MONTHS_TO_SHOW-1; $i++) {
    $date = strtotime(date('Y-m-d').' +'.$i.' month');

    $ret .=
    '<div id="viajes-rooms-month-'.$i.'" ' . ($i!=0 ? ' class="hidden"' : '') .  '>
        <div class="viajes-rooms-month-title">' .
            date('F',$date) . ' ' . date('Y',$date) .
        '</div>
        <div class="viajes-rooms-calendar">' .
            views_embed_view('room_prices', 'page_1', $hotel_nid, date('Y',$date).'-'.date('m',$date)) .
        '</div>
    </div>';
}

return $ret;
}

```

**The Javascript**

```
(function($) {
Drupal.behaviors.viajes = {
    attach: function(context, settings) {
           /*
        * Room price/availability calendar
        */

        //next button click
        $('#viajes-rooms-next', context).click(function() {
            var curr = getCurrent();

            //re-enable previous button if we've just left the first month
            if (curr == 0) {
                $('#viajes-rooms-previous', context).removeClass('disabled');
            }

            //disable next button if we've just arrived at the last month
            if (curr == (getMaxMonths() - 2) ) {
                $(this).addClass('disabled');
            }

            //roll the calendar if we're not on the last month
            if (curr < (getMaxMonths() - 1) ) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr+1), context).removeClass('hidden');
            }
        });

        //previous button click
        $('#viajes-rooms-previous', context).click(function() {
            var curr = getCurrent();

            //disable previous button if we've just arrived at the first month
            if (curr == 1) {
                $(this).addClass('disabled');
            }

            //re-enable next button if we've just left the last month
            if (curr == (getMaxMonths() - 1) ) {
                $('#viajes-rooms-next', context).removeClass('disabled');
            }

            //roll the calendar back if we're not on the first month
            if (curr > 0) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr-1), context).removeClass('hidden');
            }
        });

        //get currently visible month
        function getCurrent() {
            for (i=0; i<=(getMaxMonths()-1); i++) {
                if (! $('#viajes-rooms-month-'+i, context).hasClass('hidden')) {
                    return i;
                }
            }
        }

        //wrapper for the max_months setting
        function getMaxMonths() {
            return Drupal.settings.viajes_room_price['max_months'];
        }

    }
}
})(jQuery);

```

Just make sure you have the following classes in your CSS:

```
.disabled a {
pointer-events: none;
    cursor: default;
color: #979797;
}

.hidden {
    display: none;
}

```
> 0 votes

---
Tags: datetime, javascript
---


# Question
Title: How to filter a node reference field in content type form
I have a node reference field (User groups) in my content type; i would like to apply a filter on that field to show only the Groups belonged to the current user. How can i apply that filter in the content type insert/edit form?

# Answer
> 1 votes
I've written step by step instructions on how to do that.

Your setup will be a bit different since you don't use flags. "Step 3" describes how to use the "views reference" feature to show the referenced nodes on your node/add,edit page using views.

---
Tags: 7, entities
---


# Question
Title: How can I check whether a username is in use?
On creating a "course" content, i am creating a dummy user as its "instructor". Here is the related question.

I wasn't able to add a condition to the rule that creates the user, that checks whether a user with that name already exists. If it does, then the action (create new user) will not fire.

How can I do that?

I am using rules module with drupal 7.

# Answer
> 4 votes
You need add the condition for if the user exists or doesn't exist and then you are able to create two actions, depending on the user exists or not.

The problem is that this is not possible to do with Rules out of the box. It's not hard to add a condition like this, but it required custom code in a custom module. If this is not an option, what you are asking for is impossible *AFAIK*, as it doesn't exist.

# Answer
> 4 votes
In Rules 7.x-2.2, checking if a user exists is possible with no custom coding. See the Rules maintainer's explanation

To check if a user exists, use the following:

1. Condition: "Entity exists by property
2. Entity Type: "User"
3. Property: "Name" (or any other user field);
4. Value: "instructor name" (based on your related post; otherwise this would be the ).
5. Negate this condition. (so that the rule will not fire if a user exists)

This can be done either in one reaction rule or as an e.g. "condition" component. If using the component, it's vital to pass the node object to the component (in component settings) as a variable so that "instructor name" is available in the component.

As I noted in your related question that you will almost always want a prior condition that ensures the content type in question contains is of type "course". Otherwise, this rule will run when you either may not want it to or it should not run.

---
Tags: rules, users
---


title: Create user on content creation

text:
# Question
Title: Create user on content creation
In a "course" content type, I have an "instructor name" field, which points to a registered user.

When the "course" content is saved, I need to check if there are any registered users with the name in the "instructor name" field. If there is, I'd like to relate the created content with his id. If not, I'd like to create a new user (a dummy user maybe) and relate the content with that user.

Is this possible without php coding, just using modules? And if it is, how? I am a new drupal user with .net background and have no knowledge of php.

# Answer
Yes, you can do it with Rules module.

Basically, after enabling the Rules & Rules\_UI module, you create a new Rule acted on a node is created, add an action of creating a new user entity. You need to spend a bit of time to specify the condition to suit your need.

Some screenshot of flow attached for you.

*
*
*
*
> 7 votes

# Answer
As previously indicated, you can do this with the Rules module. However, there are a few specifics that are quite important. Moreover, there's better ways to go about doing what you're trying to do.

How to solve your question:

1.0 Create a "reaction" rule (at www.example.com/admin/config/workflow/rules/reaction/add);

1.1 React on Event: "After saving new content";

Note that there are a few other possibilities here that depend on your situation. Depending on exactly what you want to happen, it may be more appropriate to react on "Before saving new content" or even "After updating content". Each possibility will dictate it's own subsequent configuration.

2.0 Add Condition: "Content is of Type" (to ensure the rule only fires when it's "Course" content);

2.1 Content: "Node"

2.2 Content Type: "Course" (or )

3.0 Add Condition: "Entity exists by property" (to check that user name does not exist)

3.1 Entity Type: "User"

3.2 Property: "Name" (or any other user field);

3.3 Value: "instructor name" (based on your related post; otherwise this would be the ).

3.4 Negate this condition. (so that the rule will not fire if a user exists)

4.0 Add Action: "Create a New Entity"

4.1 Entity Type: "User"

4.2 Name: "Node:created:instructor\_name" (note that you want the "instructor name" field)

4.3 email: (if creating dummy users you will most likely want an "example.com" address so that no email is ever sent.)

Note that you will need to either provide a valid email or to build it with the available tokens i.e. @example.com. Otherwise, this rule will silently fail - which is why it is often a best practice" to check that what you expected actually happened and notify you if it didn't.

This rule will do exactly what you asked - test if a user exists with the same username as the new course content's "instructor Name" field, and add the user if no user exists. The problem is that your question presupposes a less than optimal solution.

What happens when you have a second course with a different "dummy" user? Do you have any method to tell which are real and which are dummy users? Is it acceptable practice in your application to i.e. display "Taught by DummyUser" to the real user? What happens if the real instructor identified is not an instructor?

Rather than deal with those and many more issues related to dummy users, why not re-frame your question and ask how to relate courses to instructors when the instructor A) exists, and B) does not exist?

If you re-frame your question, there's any number of answers ranging from simple to very sweet. The benefit is that since the data model then matches reality, you avoid all these weird issues that themselves need dealing with.

On the one hand, the answer could be simply don't make the "instructor name" field required. On the other hand, it could add: using the Views module to list only those courses that do not have an instructor. Further, use the Contextual Administration module to provide a way to add a user AND automatically associate it with the course.

As noted by others, Johan Falk at Node One has done a wonderful job explaining all the details in a number of screen-casts.
> 4 votes

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


# Question
Title: Problem with JS converting module form d6 to d7
I am converting a module from d6 version to d7 and I encountered some javascript problems.In the following code below .each() function isnt getting fired.But the its going till the .attachVote function for sure. Is this correct way to do it, or am I missing something?????

```
(function ($) {
/**
 * Create the smackdown object/namespace.
 */
Drupal.smackdown = function() {};

/**
 * Attach the smackdown behavior to nodereferences on the page.
 *
 * @param context
 *   The jQuery object to apply the behaviors to.
 */
Drupal.behaviors.smackdown = {
 attach: function(context, settings) {
    if (typeof Drupal.settings.smackdown !== 'undefined') {
        var field_1 = '.field-' +        Drupal.settings.smackdown.field1.name.replace(/_/g, '-');
         var field_2 = '.field-' +  Drupal.settings.smackdown.field2.name.replace(/_/g, '-');
         if (Drupal.settings.smackdownPerm == 1) {
             Drupal.smackdown.attachVote(context, field_1 + ' .field-item a');
             $(field_1 + ' .field-item a').attr('rel', Drupal.settings.smackdown.field1.nid).addClass('smackdown-processed');
            Drupal.smackdown.attachVote(context, field_2 + ' .field-item a');
            $(field_2 + ' .field-item a').attr('rel', Drupal.settings.smackdown.field2.nid).addClass('smackdown-processed');
        }
    else {
         Drupal.smackdown.attachNotice(context, field_1 + ' .field-item a');
         Drupal.smackdown.attachNotice(context, field_2 + ' .field-item a');
     }
   }
 }
};

/**
 * Attach the smackdown behavior to a particular link.
 *
 * @param context
 * @param selector
 *   jQuery selector for links to attach behavior to.
 */
Drupal.smackdown.attachVote = function(context, selector) {
 $(selector, context).each(function() {
     var $element = $(this);
     // Attach the on-click popup behavior to the element.
     $element.click(function(e){
     Drupal.theme('voting', $element);
     var nid = $element.attr('rel'); // not compatible with clean urls
     var sid = Drupal.settings.smackdown.sid;
     var params = {'cid':nid, 'sid':sid};
     // post nid and context to smackdown/vote
     ajaxOptions = {
       url: Drupal.settings.basePath + 'smackdown/vote/' +  Drupal.settings.smackdown.token,
      dataType: 'json',
      data: params,
      success: function(json) {
        // we put the location into a variable so that it can be changed by other modules
        location.href = json.location
      }
    };
    $.ajax(ajaxOptions);
    return false;
  });
});
};

Drupal.smackdown.attachNotice = function(context, selector) {
 $(selector, context).each(function() {
   var $element = $(this);
   $element.click(function(e) {
    Drupal.theme('notice', $element);
    return false;
   });
 });
};

Drupal.theme.prototype.voting = function(element) {
  var output = "<div id='voting-indicator'>" + Drupal.t('Voting...') + "  </div>";
 element.parent().css({'background-color':'#ffc'});
 return element.parent().append(output);
   };

Drupal.theme.prototype.notice = function(element) {
  var output = "<div id='voting-indicator'>" + Drupal.t('You do not have  sufficient rights to vote.') + "</div>";
 element.parent().css({'background-color':'#ffc'});
 return element.parent().append(output);
 };
})(jQuery);

```

# Answer
> 0 votes
Make sure that the `$(selector, context)` is valid on the page it's being called. You should be able to do this by doing a `console.log($(selector, context));` in the first line of the function.

Assuming the selector and context are valid, the `.each()` should be executed.

If they are not valid, you may have to replace the element or context being passed into `Drupal.smackdown.attachNotice()`.

---
Tags: javascript
---


title: How to alias views url with argument

text:
# Question
Title: How to alias views url with argument
I set up a view with taxonomy id as the argument and am trying to figure out how to alias the term id with its name.

Trying to turn `url.com/discussion/8 -> url.com/discussion/term` but the argument must still be the id b/c I need to to pass it by URL to a node edit form from a link on the view display.

# Answer
In your View, check the taxonomy argument and set the validator to Taxonomy Term. From there you can specify the argument type (and vocabulary where the term is expected to come from). Set the argument type to "Term name/synonym converted to Term ID" and that should help.
> 1 votes

# Answer
I came across same issue solved it with below code ! Hope it helps ! You need to write a small custom module to do this !

Using hook term insert update delete and pathauto helper function.

```
/**
 * Implements hook_taxonomy_term_insert().
 */
function your_module_taxonomy_term_insert($term) {
  // Do it only for Group Categories term
  if ($term->vid == 3) {
    module_load_include('inc', 'pathauto');
    $path = array();
    $path['source'] = 'groups/' . $term->tid;
    $path['alias'] = pathauto_cleanstring($term->name);
    path_save($path);
  }
}

/**
 * Implements hook_taxonomy_term_update().
 */
function your_module_taxonomy_term_update($term) {
  // Do it only for Group Categories term
  if ($term->vid == 3) {
    module_load_include('inc', 'pathauto');
    $conditions = array();
    $conditions['source'] = 'groups/' . $term->tid;
    $path = path_load($conditions);
    // Delete old alias if user erased it.
    if (!empty($path['pid'])) {
      path_delete($path['pid']);
    }
    $path = array();
    $path['source'] = 'groups/' . $term->tid;
    $path['alias'] = 'groups/' . pathauto_cleanstring($term->name);
    path_save($path);
  }
}

/**
 * Implements hook_taxonomy_term_delete().
 */
function your_module_taxonomy_term_delete($term) {
  // Do it only for Group Categories term
  if ($term->vid == 3) {
    path_delete(array('source' => 'groups/' . $term->tid));
  }
}

```

**Note**: Replace 3 with the vocabulary id you are using Replace source pattern 'groups/' . $term-\>tid and alias pattern with the patterns you would like to.

Hope it helps !
> 1 votes

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


# Question
Title: Problem with login/logout operations while using drupal for facebook
I'm using drupal 6 and the module drupal for facebook v6.x-3.3 and I have a problem with the logout functionality.

Strangely when I try to logout of the website, it automatically redirects me to my facebook profile. If you return to the site, I am still logged out of it.

I don't know if is a issue of javascript or module.

I had a problem with the login, because if I tried to enter the site, the site would freeze in front page and on reloading by pressing f5, it shows up in logged in state. Now, have a delay (the typical module) and you enter. Is there any way to remove the delay that has to quickly enter the website?

# Answer
> 2 votes
You can try FBOAUTH module. This module is simple and straight forward. It works out of the box with out any glitches.

Check readme file to configure Facebook Login button. Hope it resolves all your issues !

---
Tags: users, 6, social-network
---


# Question
Title: I want to get the real password(not md5 encryption) when edit the account profile via user profile form and save. how to do that?
> **Possible Duplicate:**
> How can I get the real password via hook\_user\_update()?

I want to change the current user password, and get the new password(the real password, not md5 encryption) when edit the account profile via user profile form(e.g.: example.com/user/1/edit) and save. would anyone can tell me how to do that? I tried using hook\_user\_update(), but it didn't succeed.

# Answer
> 4 votes
You cannot decrypt the password due to security reasons. Drupal 7 uses SHA512 by default with a salt. It will perform multiple hashes on the password. It's highly impossible to decrypt password.

See the better explanation provided here.

**To reset the password see the solution provided** here.

---
Tags: 7, users
---


# Question
Title: What will be the post parameter when specifying vocabulary term?
I am trying to create a drupal node with a iphone app via rest server. I want to send the request to drupal as json.

I have added a taxonomy vocabulary for categorizing the nodes. Specifying a category is mandatory when creating node.

> **My request url is**
> drupal site/ep/node.json
> **Post parameters**
> node\[title\]=mysample&node\[type\]=story&node\[body\]=sample body&node\[???\]=myCategory1

I specified title, body, and type....but **what will be the parameter name to specify the term of my vocabulary (i.e. category name)?**

I tried node\[taxonomy\], node\[term\], node\[vocabulary\], but no success. Please help!

> Config:
> Drupal 6.26
> REST Server 3.0

# Answer
> 1 votes
node\[taxonomy\]\[***vocabulary term id***\]\[tid\]=***vocabulary term id***

in place of ***vocabulary term id*** give the term id of the vocabulary term

How to get the term id? I made a custom drupal view of type term where I fetch only the fields **term id** and **term**

I then sent the view contents to my iphone app. When I choose a particular term I also have the term id.

---
Tags: taxonomy-terms, services, 8
---


# Question
Title: Background of CKEditor is black for authenticated user
I am using the CorporateClean theme for Drupal 7.15, and I have an issue using CKEditor with this theme.

When an authenticated user writes some content, the background of the CKEditor text editor (the area where the user can enter and format text) turns black. I do not have this problem when login as the admin. I also do not have this problem if I remove CKEditor.

How can I change this background?

# Answer
Do you have Firebug installed (extension for Firefox) ? With Firebug you can inspect element and see what css definition makes it black. Then, in your theme css file you can override that settings by writting your own definition to make it white. like

```
.ckebackground {
background-color:#ffffff;
}

```

where ckebackground is "problematic" class that makes it black.
> 0 votes

---
Tags: wysiwyg
---