# Question
Title: Display node author picture through tpl file
I am writing my custom node--blog.tpl.php for my Drupal7 based site. I want to print the author image of the blog so in my tpl file i include the following:

```
$user = user_load($user->uid);
  print theme_image_style(
                array(

                    'path' => $user->picture->uri,
                    'attributes' => array(
                        'class' => 'in-blog-user'
                    )
                )
            );

```

However, it does not display any image and i get a error as :

`The requested page "/sites/default/files/styles//public" could not be found`

What am i doing wrong?

Regards

PS: my pictures directory is "pictures"

# Answer
The following lines did it:

```
$user = user_load($uid);
print theme('user_picture', array('account' =>$user));

```
> 3 votes

# Answer
There is Author Pane

> Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

For the tabbed view you cold try Quick Tabs

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*.
> 0 votes

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


# Question
Title: Hundred of Thousands of database records and how to safely delete them?
Hi I've been asked to work on a Drupal commerce site and I'm not very familiar with this module.

The idea is to use an existing database and export it to 'quickstart' a new site. I'm to keep all the products but delete all the customers and transactions data. But when I look at the DB of the existing site it's packed with hundreds of thousands of stuff that I don't understand.

The product catalog only includes 50 or 80 products or so but in the database I see an incredible number of rows in some of the table and I don't know how I can safely remove all this data without breaking the database. Here is what I see in php/myadmin:

```
field_revision_commerce_unit_price   ~210,219 InnoDB    utf8_general_ci 129.7 MiB   -
field_revision_commerce_total    ~211,353    InnoDB utf8_general_ci 128.7 MiB   -
field_data_commerce_unit_price   ~210,696    InnoDB utf8_general_ci 128.6 MiB   -
field_data_commerce_total    ~209,449    InnoDB utf8_general_ci 127.6 MiB   -
field_revision_commerce_order_total ~210,849 InnoDB utf8_general_ci 125.5 MiB   -
field_data_commerce_order_total  ~210,129    InnoDB utf8_general_ci 119.5 MiB   -
field_revision_commerce_product  ~210,384    InnoDB utf8_general_ci 82.5 MiB    -
field_data_commerce_product  ~210,384    InnoDB utf8_general_ci 81.4 MiB    -
field_revision_commerce_line_items ~211,257  InnoDB utf8_general_ci 81.4 MiB    -
field_revision_commerce_display_path ~210,521 InnoDB    utf8_general_ci 77.5 MiB    -
field_data_commerce_display_path ~210,521    InnoDB utf8_general_ci 76.4 MiB    -
field_data_commerce_line_items   ~210,393 InnoDB    utf8_general_ci 75.4 MiB    -
field_revision_field_dept_date   ~210,384    InnoDB utf8_general_ci 69 MiB  -
field_data_field_dept_date ~210,384 InnoDB  utf8_general_ci 68.9 MiB    -
commerce_line_item   ~211,134 InnoDB    utf8_general_ci 34.6 MiB    -
commerce_order   ~210,442 InnoDB    utf8_general_ci 34.1 MiB    -
commerce_order_revision ~212,036 InnoDB utf8_general_ci 26.1 MiB    -

```

I'm really lost here isn't there a quicker way to delete all the unnecessary data while keeping the product catalog intact? Thanks

# Answer
Forget about accessing the database manually, you will just break things.

For mass-deletion create a VBO-based view.

Same thing for export, you will want to export whole entities, not tables.
> 2 votes

# Answer
You can create a view with all your nodes you want to delete, be careful to select only good node types

Browse the view result in a custom module. First, do it safely without node\_delete\_multiple() ! Do it on a backuped DB !

```
$view = views_get_view ('your_view_name');
$view->execute();

if(count($view->result) > 0){
  //dpr($result); //print the result before to delete
  $deletelist = array();
  foreach($view->result as $result){
    $deletelist[] = $result->nid; // check this is the right fieldname in your view result
  }
  //node_delete_multiple($deletelist); // only when you are sure !
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Control where a new field is stored in the database D7
I am interested in adding a field to the 'Product' content type in Ubercart 3 / Drupal 7. I have read up on topics like field\_create\_field() and `db_add_field()` but I want my field to be stored as an additional column in the `uc_products` table in my database. In addition, I want my new field (qid) to be called whenever I call up the `$node` value. How would I go about doing this?

# Answer
This is no longer done in D7. You will want to use a proper field (which is stored in its own table and has many benefits over a simple column).
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: Hide webform components after submission
I'm trying to autohide all my webform components after submission. I've tried to add an extra submit handler to the form, but no luck there.
The webform is posted by using AJAX (but nothing is shown in my Console).

Is there some module or hook I'm overlooking?

# Answer
> 1 votes
I managed to do so with a hook\_form\_FORM\_ID\_alter:

```
function mymodule_form_myformid_alter(&$form, &$form_state, $form_id) {
    if(!empty($form_state['input'])) {
      $items = array('name', 'firstname', 'zip', 'phone', 'email');

      foreach ($items as $value) {
        $form['submitted'][$value]['#type']     = 'hidden';
        $form['submitted'][$value]['#title']    = '';
        $form['submitted'][$value]['#required'] = 0;
      }
      $form['actions']['#type'] = 'hidden';
    }
  }

```

It's not the most clean way to do so, but it does the trick :)

---
Tags: 7, ajax, webforms
---


title: User Profile Edit workflow

text:
# Question
Title: User Profile Edit workflow
any module available, to implement a work flow when user is trying edit the user profile fileds (custom fields). Following is my use case

1) User can edit the profile field , but admin approval is required to update it
2) Admin can either approve or reject the profile update
3) If it is approved need to change the user role , and need to send an email to the user
4) If rejected , need to trigger an email again

Thanks

# Answer
> 1 votes
There is need to work with Rules module make such action, "send email", "change role".

The workbench module is very popular, but is for Drupal 7 only. can be achieved good results using the revisioning module, which has a release for Drupal 6.

---
Tags: users, workflows
---


# Question
Title: Converted CSS/HTML theme to D7, .js files ignores integrated jQuery and works only with jQuery imported via .info
I got a basic static CSS/HTML theme which is using some .js like jcarousellite.js and it has a jquery file together which is jquery-1.4.2.min.js

So I import that jcarousellite.js via theme's .info:

```
scripts[] = js/jcarousellite.js

```

Then there is some inline script which goes with that template, so I pasted that to my html.tpl.php

```
    $(function() {
         $(".carousel").jCarouselLite({
                    btnNext: ".next",
                    btnPrev: ".prev"
         });
});

```

Now, to make it all work, it needs jQuery. So since D7 loads jQuery by default from its core (and it does load it and current version is 1.4.4 that comes with Drupal 7.21) I understand that the jquery-1.4.2.min.js which comes together with static template is not needed right? So I do not add it to my .info and after flushing caches and everything, it loads my jcarousellite.js and it loads inline .js, but it doesn't work.

If I load that jquery-1.4.2.min.js via .info then all .js is working on the website. So what I am missing? How to make it work without importing that older jquery library via .info and using the jQuery from Drupal's core? Now both and core jQuery and that custom jQuery libraries are loaded at same time.

# Answer
add a anther js file via theme's .info;

```
scripts[] = js/mycustomscript.js

```

dont add your inline script in html.tpl.php , add it in `mycustomscript.js` file like

```
(function ($) {

  Drupal.behaviors.exampletheme = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev"
     });
    }
  };

})(jQuery);

```
> 9 votes

# Answer
The `$` global will no longer refer to the jquery object. However, with this construction, the local variable `$` will refer to jquery, allowing your code to access jQuery through `$` anyway, while the code will not conflict with other libraries that use the `$` global.

http://drupal.org/update/modules/6/7#javascript\_compatibility
> 3 votes

---
Tags: 7, theming, javascript
---


# Question
Title: How to add back button for specific content?
Just realised all my pages are now displaying a back button with this code I added to node.tpl.php `<FORM><INPUT Type="button" VALUE="Back" onClick="history.go(-1);return true;"></FORM>`

Is there a way to change the code to include only some node content types?

# Answer
> 5 votes
Duplicate your `node.tpl.php` file (in your theme's folder) and rename it to `node--[content type].tpl.php`. Use machine name of the content type, which can be found in Administer \> Structure \> Content Types Replace content type with name of your content type. (i.e for page content type, `node--page.tpl.php`)

Don't forget to flush all caches when you have placed the new code in this new template.

Drupal will now use this custom template file for this node type, and the `node.tpl.php` base template for other types.

---
Tags: nodes
---


title: Trouble setting up field instance

text:
# Question
Title: Trouble setting up field instance
I have isolated my error to the `field_create_instance($instance)` line but can't make sense of what I'm doing wrong.

```
function my_module_quote_add_qid() {
$field = array(
    'field_name' => 'qid',
    'type' => 'text',
  );
  field_create_field($field);
  $instance = array(
    'field_name' => 'qid',
    'entity_type' => 'node',
    'bundle' => 'product',
    'label' => t('qid'),
    'widget' => array(
      'type' => 'textfield',
    ),
  );
  field_create_instance($instance);
}

my_module_quote_add_qid();

```

This is what my error looks like:

```
Notice: Undefined index: view modes in EntityDefaultRulesController->eventInfo() (line 51 of /var/www/seven/sites/all/modules/entity/entity.rules.inc).
Notice: Undefined index: schema_fields_sql in DrupalDefaultEntityController->buildQuery() (line 265 of /var/www/seven/includes/entity.inc).
Recoverable fatal error: Argument 2 passed to SelectQuery::fields() must be an array, null given, called in /var/www/seven/includes/entity.inc on line 284 and defined in SelectQuery->fields() (line 1300 of /var/www/seven/includes/database/select.inc).

```

# Answer
SOLVED:

According to the documentation, the only required properties are field\_name, entity\_type and bundle. So I commented out:

```
'label' => t('qid'),
'widget' => array(
  'type' => 'textfield',
),

```

And now the field and instance install and uninstall properly. I'm fairly sure `'textfield'` is an inappropriate widget type.
> 0 votes

---
Tags: entities
---


# Question
Title: How do I migrate users passwords from Drupal 6 to Drupal 7?
I am trying to migrate users from a Drupal 6 to a Drupal 7 site. My problem is how to change their password from MD5 to the hash one (used by D7).
Do you have any idea?

# Answer
> 11 votes
To update the md5 password to the hashed one I needed to use user\_hash\_password() and concact an 'U'. Here is the script that I used to make it work.

```
<?php
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
        $res = db_query('select * from drupal.users');

        if($res) {
                foreach ($res as $result) {
                        $hashed_pass = user_hash_password($result->pass, 11);
                        if ($hashed_pass) {
                          $hashed_pass  = 'U' . $hashed_pass;
                          db_update('users')->fields(array('pass' => $hashed_pass))->condition('uid', $result->uid)->execute();
                        }
                }
        }

```

Then I ran

```
drush scr <name_of_the_script_file>

```

And it worked.

# Answer
> 7 votes
There is a VERY simple answer to this:

```
<?php
  $this->destination = new MigrateDestinationUser(array('md5_passwords' => TRUE));
  ...
  $this->addFieldMapping('pass', 'source_password');
?>

```

Reference: Preserving user passwords

# Answer
> 5 votes
If somebody needs a standalone PHP script to migrate users from Drupal 6 to Drupal 7, then here it is:

```
  <?php
    /*
    Standalone PHP script to migrate users from Drupal 6 to Drupal 7 programatically.
    Date: 9-4-2012
    */

    // set HTTP_HOST or drupal will refuse to bootstrap
    $_SERVER['HTTP_HOST'] = 'example.org';
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';

    //root of Drupal 7 site
    $DRUPAL7_ROOT="/var/www/ace";
    define('DRUPAL_ROOT',$DRUPAL7_ROOT);
    chdir($DRUPAL7_ROOT);
    require_once "./includes/bootstrap.inc";
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    require_once "./includes/password.inc";

    //connect to Drupal 6 database
    //syntax:mysqli(hostname,username,password,databasename);
    $db= new mysqli('localhost','ace6','ace6','ace6');
    if(mysqli_connect_errno())  {
        echo "Conection error. Could not connect to Drupal 6 site!";
        exit;
    }

    //get users from Drupal 6 database
    $query="select * from users";
    $result=$db->query($query);
    //count number of users
    $num_results=$result->num_rows;
    for($i=0;$i<$num_results;$i++){

        //fetch each row/user
        $row=$result->fetch_assoc();

        //migrate only active users
        if($row['status']==1){

            //convert password from Drupal 6 style to Drupal 7 style
            $hashed_pass='U'.user_hash_password($row['pass'],11);

            //check if user with same email address already exists in Drupal 7 database, if it does, do not migrate
            if (!user_load_by_mail($row['mail'])) {
                $account = new stdClass;
                $account->is_new = TRUE;
                $account->name = $row['name'];
                $account->pass = $hashed_pass;
                $account->mail = $row['mail'];
                $account->init = $row['mail'];
                $account->status = TRUE;
                $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
                $account->timezone = variable_get('date_default_timezone', '');
                //create user in Drupal 7 site
                user_save($account);
                //print message
                echo "User acount ".$row['name']." has been created\n";
            }
        }

    }
    ?>

```

# Answer
> 3 votes
Well, if you *upgrade* you come out with your passwords OK. I guess you could probably look at the upgrade code to see how they do that.

However, if you're just migrating users, probably the most likely approach would be just to send out one-time login links to everybody and get them to reset their passwords.

# Answer
> 0 votes
If I ran this from devel/php on the D7 site, I found I only needed:

```
require_once "./includes/password.inc";

//connect to Drupal 6 database
//syntax:mysqli(hostname,username,password,databasename);
$db= new mysqli('localhost','ace6','ace6','ace6');
if(mysqli_connect_errno())  {
    echo "Conection error. Could not connect to Drupal 6 site!";
    exit;
}

//get users from Drupal 6 database
$query="select * from users";
$result=$db->query($query);
//count number of users
$num_results=$result->num_rows;
for($i=0;$i<$num_results;$i++){

    //fetch each row/user
    $row=$result->fetch_assoc();

    //migrate only active users
    if($row['status']==1){

        //convert password from Drupal 6 style to Drupal 7 style
        $hashed_pass='U'.user_hash_password($row['pass'],11);

        //check if user with same email address already exists in Drupal 7 database, if it does, do not migrate
        if (!user_load_by_mail($row['mail'])) {
            $account = new stdClass;
            $account->is_new = TRUE;
            $account->name = $row['name'];
            $account->pass = $hashed_pass;
            $account->mail = $row['mail'];
            $account->init = $row['mail'];
            $account->status = TRUE;
            $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
            $account->timezone = variable_get('date_default_timezone', '');
            //create user in Drupal 7 site
            user_save($account);
            //print message
            echo "User acount ".$row['name']." has been created\n";
        }
    }

}

```

Both sites were on the same webserver.

---
Tags: users, migrations
---


# Question
Title: Suddenly my website front page was not found!
My websites richtown.ae, and hannahaicah.com suddenly are not showing the front page; the rest of the pages is working fine. My hosting provider changed the php.ini file this morning, due to problems with PDO. Can anybody tell me what happened?

I also changed the path for the front page but nothing happened.

# Answer
Edit your .htaccess and the setup of your subdomain.richtown.ae... frontpage on a subdomain?

```
# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

```
> 1 votes

---
Tags: 6
---


title: multiple content items on one page

text:
# Question
Title: multiple content items on one page
Hope that someone can help me with this question.

I am using the latest version of Drupal 7.

I appreciate that what I am trying to do can in part be achieved with Views, Panels, combinations of the aforementioned or other things like taxonomy and CCK. Perhaps I am not understanding them fully enough to get their full power. However, I am hoping that there is perhaps a module to do what I want to do. As I said, I know I can do some of what I want to do using Views and Panels but I can only figure out how to do what I want to do on a specific 'page' by 'page' basis by using the interface provided in the views and/or panels sections for each specific page. What I am want is a more dynamic way of creating a view without having to go through the process of creating a view each time.

I know that nodes are not traditionally used as I want them to be. However, I want to be able to give an admin user the ability to place multiple content types (multiple nodes) on the same 'page' without having to design their own view and/or panel set up for each 'page'. For example on one page they may want to put a content type called Article, then beneath that article they want to put a Video, under that a basic page, then an Image, then an image with a text wrapped around it and then another specific article and so on. There could be any combination of the content types (nodes) on each page and any number of pages.

I appreciate that generally speaking a "basic" node is generally considered or rendered as an individual "page" or grouped together in some way to display as a blog BUT I want to give an admin user the ability to dynamically combine any node not just the type with an easy to use interface. Even it is just drop down menus of the different content types. I also want to give them the ability to move these up and down the page preferably using drag & drop or at least a text box to put in the weight of each item.

I have found the command "node\_view" and can sort of see a way of using that but I wouldn't know how to use it in a dynamic way or how to set it up for use on user created "pages". I am fairly new to Drupal and I maybe barking up the wrong tree. Perhaps there is already a module out there that I haven't found.

Thanks in advance for any help...

# Answer
we had a similar requirement for a site we built recently. In this case we ended up creating a content type representing a "page" with entity reference fields used to pull in the other content to be displayed.

We also used the Entity Connect to make the users' lives a bit easier by providing the ability to add new content from within the page edit form.

So just to clarify, there's one content type you might call a "page" or "container", and several other content types used to comprise its contents. Each entity reference field was laid out in a different area of the page when displayed, and could have multiple values.
> 1 votes

# Answer
I would recommend to take a look at the Context module. It's probably one possible way to achieve what you want.

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

A context can be a path to a specific node for example. Or when a view is viewed. This can trigger reactions like putting a block into a region or display a view in another region or at a specific position in a region.

This can be managed through a UI with drag an drop.

Once you get familiar with the concept, you'll love it... ;)
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How can i change registration email send to admin
I was wondering how to change the standard text in the email send to the administrator when a new user has registered.

Is there a way to change the text? Maybe the same way as you can change the emails send to the user when registered?

thanks

# Answer
Unlike normal users there's is no UI to change the text of the message sent to administrator on account creation.

You could implement hook\_mail\_alter(), to achieve this via a custom module:

```
function MODULE_mail_alter(&$message) {
  if ($message['id'] == 'user_register_pending_approval_admin') {
    //$message['body'] is the array you want to change.
    $message['body'][] = 'Your custom message for admin goes here.....';
  }
}

```
> 5 votes

# Answer
The Mail Edit module allows you to alter mail templates including the one you mention, which appears on its list with the key "register\_pending\_approval\_admin".
> 2 votes

# Answer
One way is to use the rules module

You create an action (send an email) on a user creation event
> -1 votes

---
Tags: emails, users
---


# Question
Title: How to replace an unfiltered Search API results view with custom text?
**Setting:** using the `search_api_views` module, I have created a view with an exposed fulltext search filter. In addition, I have lots of facets for the corresponding search index in a separate block (via the `search_api_facetapi` module). Searching and filtering works well.

**Question:** When no facet item is selected and no fulltext search is used, then all indexed nodes are shown in the view as search results. How can I replace this full nodes list with a custom text (e.g., “Enter a search term or select a facet item to filter our products.”)? In other words: how can I hide the results list if and only if no search filter (facet or fulltext) is applied?

# Answer
> 0 votes
Here’s how I solved this:

First I implemented `hook_views_post_build`. Note, that I could have probably used most other views processing hooks, too, as I’m only adding custom build information.

```
/**
 * Implements hook_views_post_build().
 */
function MY_MODULE_views_post_build(&$view) {

  // If there is no explicit search being done, then we show a message instead
  // of all search results. We still have to run the search under the hood so
  // that we have correct search facets available. Therefore we could have also
  // used most other views processing hooks here.
  if ($view->name === 'MY_VIEW_NAME' && empty($view->exposed_input['f'])
       && empty($view->exposed_input['search'])) {
    $view->build_info['MY_MODULE_show_message'] = TRUE;
  }
}

```

Then I added my custom message to an overridden `views-view.tpl.php` using the previously defined build info variable:

```
<!-- … views template header here … -->
<div class="<?php print $classes; ?>">

  <?php if (isset($view->build_info['MY_MODULE_show_message'])): ?>
    <h2>My Custom Message</h2>
    <p>Enter a search term or select a facet item to filter our products.</p>
  <?php else: ?>
    <!-- … normal views content here … -->
  <?php endif; ?>

</div><?php /* class view */ ?>

```

---
Tags: views, search
---


# Question
Title: How do I insert the title of the block between two Views fields?
A designer has sent me a very cool design, and I don't know which is the **.tpl** file I need to override.

Basically, I need to put the title of the block between two fields of a view. The view is already a header of another view, and it displays only one record.

Other (bad) alternatives I see:

* Do some positioning tricks with CSS.
* Create a *custom text* field and style it like if it was the block title, and then hide the block title.

# Answer
You could try Views block area

> This module exposes all available blocks as a views area. This way you can add any block inside a footer or header from your view.

Also there is Views Hacks

Or i would do it with Views PHP by adding a field and print the block there with https://drupal.stackexchange.com/a/14354/4471
> 2 votes

# Answer
From here: http://themery.com/book/export/html/91 you need to create a file named like block--MODULE--DELTA.tpl.php

So for a views block I believe it's block--views--VIEWNAME-DISPLAYNAME.tpl.php
> 2 votes

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


# Question
Title: webTestCase->drupalPost() or drupal_http_request()?
I'm writing a simpletest for a module that posts XML directly to a URL (it's on a closed system so there's no user or auth or anything at this point).

I've manually tested getting the response code by using `drupal_http_request()` to POST the file, but since I'm now doing the same thing in an actual simpletest, I feel like I should use `webTestCase->drupalPost()`.

The only problem is that `drupalPost()` seems to expect a save button value. I'm not POSTing via a form with a submit button, so can I still use `drupalPost()`? Or should I just use `drupal_http_request()` in my simpletest?

# Answer
> 2 votes
As said in the documentation page for DrupalWebTestCase::drupalPost(), that method supposes to be called for a Drupal page containing a form; if that is not the case, you should use `drupal_http_request()`.

The reason is that the method tries to emulate a click on a submit button, as said in the description for the `$submit` parameter.

> `$submit`: Value of the submit button whose click is to be emulated. For example, `t('Save')`. The processing of the request depends on this value. For example, a form may have one button with the value `t('Save')` and another button with the value `t('Delete')`, and execute different code depending on which one is clicked.

---
Tags: testing
---


# Question
Title: During form validation, can you "stash" a form for an end user while they fill out a different form?
## Core of the question

I have a form that might throw a validation error based on the values in other entities on the site. If a user fills out an entity form and hits submit, they will see validation errors that tell them another entity is in conflict.

I would like to provide the user with an option to update the other entity on the site to clear up the validation issue. The problem with that, however, is that the user would have to navigate away from the form throwing the validation errors, and they'd then lose their input.

I would like to fix this up without using Ajax, because I think that Ajax will complicate the UI and I'd like to keep javascript out of the equation for now.

Is there a standard non-hackish way to use `$form` and `$form_state` in a way that will allow me to just grab the user input and stash it into the SESSION or something so once the user fills out a secondary form, they go back to the original form and their originally input values are still there?

## The desired user experience

1. `{Entity A}` exists with field data on the site that will cause a validation error on `{New Entity B}` add form.
2. User enters field input into `{New Entity B}` add form, and hits submit.
3. My custom `{New Entity B}` form validation callback checks `{Entity A}` and discovers a problem that requires `{Entity A}` to be edited before `{New Entity B}` can be saved.
4. User does `???` and `{New Entity B} $form` and `{New Entity B} $form_state` are "saved for later" while user goes to `{Entity A}` edit form.
5. User updates and saves `{Entity A}` and is redirected back to `{New Entity B}` add form. `{New Entity B}` add form has the same input values the user already entered, because they were retrieved from a "stashed" `{New Entity B} $form` and `{New Entity B} $form_state`.

Is this possible? How?

## Edit

### Caveat about uncertainty of form fields

The exact fields on the entity form are unknown. I want to apply this logic to numerous entity forms, which means I don't know which fields are there in my validation callbacks. This is why I'm looking to stash `$form` and `$form_state` in their entirety. I don't want to get involved with individual field values.

# Answer
I just looked at your Entity Availability project page, and it looks interesting. You are facing the classic Temporal dependency problem of all scheduling systems (eg Departure time depends on Arrival time). This is the one data dependency which cannot be resolved statically.

The Webforms module uses $\_SESSION to store information for multi-page forms for the anonymous user. In the case of the Webform module, the submission ID ($sid) is saved the $\_SESSION, and the $form\_state is saved in and retrieved from the database, however I see no problem with using $\_SESSION to maintain a working copy of the $form\_state object ($\_SESSION\['form\_id'\] = $form\_state;). However, I would suggest you look at a cache\_entity\_availability table keyed on, perhaps, form\_id and uid, just in case the session expires (servers down, network problem etc).

Thanks for the additional info, and good luck with the project.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Is EntityFieldQuery really this inefficient?
I am an admitted newbie to the Entity API, but am trying to cure that. I'm working on a site that uses a number of content types with various fields attached to them; nothing fancy. So, when I want to retrieve a set of entries, I have been, in my ignorance, calling directly down into the database and doing something like this:

```
$query = db_select('node', 'n')->extend('PagerDefault');
$query->fields('n', array('nid'));
$query->condition('n.type', 'my_content_type');

$query->leftJoin('field_data_field_user_role', 'role', 'n.nid = role.entity_id');
$query->condition('role.field_user_role_value', $some_value);

$query->leftJoin('field_data_field_withdrawn_time', 'wt', 'n.nid = wt.entity_id');
$query->condition('wt.field_withdrawn_time_value', 0);

$query->orderBy('n.created', 'desc');

$query->limit(10);

$result = $the_questions->execute()->fetchCol();

```

(yes, I could probably collapse a bunch of these lines into a single `$the_questions->` statement; pls ignore that for now.)

Trying to rewrite this with EntityFieldQuery, I come up with:

```
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->fieldCondition('field_user_role', 'value', $some_value)
  ->fieldCondition('field_withdrawn_time', 'value', 0)
  ->propertyOrderBy('created', 'desc')
  ->pager(10);

$result = $query->execute();

if (isset($result['node'])) {
    $result_nids = array_keys($result['node']);
}
else {
    $result_nids = array();
}

```

which gives me the desired results and is surely much prettier.

So, now I'm wondering about performance. As a start, I throw each of those bits of code into a stupid `for()` loop, capturing `time()` before and after execution. I run each version 100 times over a not-very-big database, and get something like this:

* Direct version: 110 msec
* EFQ version: 4943 msec

Obviously I get different results when I re-run the test, but the results are consistently in the same ballpark.

Yikes. Am I doing something wrong here, or is this just the cost of using EFQ? I have not done any special database tuning with respect to the content types; they're just what comes from defining the content types in the usual, form-based way. Any thoughts? The EFQ code is definitely cleaner, but I really don't think I can afford a 40x performance hit.

# Answer
> 10 votes
The `EntityFieldQuery` class is as efficient as its requirements allow it to be. It needs to be compatible with any field storage classes, even with those that use a NoSQL engine to store the field data, such as the one that uses MongoDB. For that reason, `EntityFieldQuery` cannot directly query the database, because the current field storage backend might not use an SQL database at all.

Even in the case the field storage uses a SQL engine to store its data, the equivalent of `$query->leftJoin('field_data_field_user_role', 'role', 'n.nid = role.entity_id'); $query->condition('role.field_user_role_value', $some_value);` for the `EntityFieldQuery` class requires:

* Code to build the database table name from the field name
* Code to build the condition to use to join the table containing the field data with the table containing the entity data
* Code to build the name of the database row containing the field data

The difference is immediately visible: In one case you are using three litteral strings, while in the other case there is code that (in the simplest of the cases) is concatenating strings.

As per your comment about code that checks if the user has the permission to access the fields, you can bypass that using the following line to the code using the `EntityFieldQuery` class.

```
$query->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

```

This works if you are using Drupal 7.15, or higher; for earlier versions, you should use the following code.

```
$account = user_load(1);
$query->addMetaData('account', $account);

```

As usual, you should not bypass the access permission if the code could show to the user information to which the user should not have access. This is similar to what is done from Drupal when an unpublished node is only shown to the users who have the permission to see unpublished nodes. If the code's purpose is, for example, selecting some entities that are successively deleted (e.g. during cron tasks), then by-passing the access control doesn't make any harm, and it is the only way to proceed.

---
Tags: 7, database, entities
---


# Question
Title: How do I store the input value on form submission?
I made a simple form in a module with a textfield and a submit button. Every time I type something into the textfield and submit, when the page loads, the default value is in the textfield. I followed the tutorial on http://www.badzilla.co.uk/Drupal-7-Tutorial--Form-Block-With-Template-File

Every #value property is set to whatever I type into the textfield under $form and $form\_state except #default\_value.

What am I missing?

Here is the code

```
<?php

function my_form_block_info() {
  $block = array();

  $block['my_form_block'] = array(
    'info' => t('My Form'),
    'weight' => 0
    );
    return $block;
}

function my_form_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'my_form_block':
      $block['title'] = t('Sample form in block');
      $block['content'] = drupal_get_form('my_form_form');
      break;
  }
  return $block;
}

function my_form_form($form, &$form_state) {
  $form['name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => 'some default value',

  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
    '#validate' => array('my_form_validate'),
    '#submit' => array('my_form_submit'),
  );

  $form['#theme'][] = 'my_form';
  return $form;
}

function my_form_validate($form, &$form_state) {

return TRUE;
}

function my_form_submit($form, &$form_state) {

    drupal_set_message(t('Hello :name - how are you?', array(':name' => $form_state['values']['name'])));

    $input = $form_state['input']['name'];
    $form_state['values']['name'] = $input;
}

function my_form_theme() {

    return array(
        'my_form_form' => array(
            'arguments' => array('form' => NULL),
            'render element' => 'form',
            'template' => 'my_form',
        ),
    );
}

```

# Answer
I would have thought you would be able to do something like this in your form handler...

```
'#default_value' => $form_state['post']['name'] ? $form_state['post']['name'] : 'some default value',

```

...but perhaps since this is in a block, it is being called "fresh" each time the page is displayed.

So, quick and dirty (and possibly all hideously wrong) the following does work...

```
'#default_value' => $_SESSION['foo_bar_baz'] ? $_SESSION['foo_bar_baz'] : 'some default value',

```

...if you put...

```
 $_SESSION['foo_bar_baz'] = $form_state['values']['name'];

```

...in your submit handler. At least for logged in users anyway, and will persist during his/her session.

Hopefully there is a "drupaler" way of doing this, but in the meantime, flame retardant suit on.
> 1 votes

# Answer
You need to save the form values as variables in your `my_form_submit` function using `variable_set()`:

```
variable_set('myform_name_value', $form_state['input']['name']);

```

Then pull the stored value back out with `variable_get()` as the default value when displaying the form field in `my_form_form()`:

```
$form['name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => variable_get('myform_name_value', 'some default value'),
);

```

Note that when you set variables with a module in Drupal, you shouuld also include an `.install` file that deletes the variables if the module is ever uninstalled.
> 1 votes

---
Tags: forms
---


# Question
Title: Make variables outside of node available to pathauto
I'm trying to port a website over to Drupal 7. The structure consists of locations which have an entity reference to a region which has an entity reference to a country:

> location\<-region\<-country\<-continent

This all seems to work OK. A location node doesn't directly know what country it is in, but it does know what region it's in.

The **problem** is I want to use the old URL structure:

> /continent/country/region/location

So far I can get it to work for `/region/location` (as region is referenced from location) but then I get stuck.

What I'm wondering is there any way to pull these other fields (country / continent) into the node and make them available to pathauto?

If it helps it doesn't really matter what the continent and country are as region & location provide enough info. So a wildcard would be fine.

So, firstly, is this possible with this structure. And if so, how?

Any help greatly appreciated.

# Answer
I was in a similar boat with a site I was working on recently. Unfortunately, Drupal 7 does not fully support tokens on field entities; see http://drupal.org/node/691078. This is why the "location node" type exists in the location module -- it is easier to define tokens for your locations. However, I did not like the UX for location nodes; I greatly preferred the result that can easily be obtained with cck locations.

Since it was not possible to easily support tokens on cck locations, I instead wrote my own custom token code in my custom module for my site. I did spend quite a few hours trying to do the former first, before giving it up as much too large of an effort.

I'm not sure if you are using the location module, or if you are just defining your own entities that happen to contain locations. The fact that you have your location entities chained together implies that you're using your own entity types. Here's the result I came up with for the location module; you should be able to adapt it for standard entities without much trouble. The code below could probably use some minor improvements; 'und' should be LANGUAGE\_NONE, the special-checking for a specific content type is probably unnecessary, etc.; it shouldn't be too hard for you to adapt in some code that resolves your chained entity references to build the tokens you need.

Once you've written your code, it's easy to select your new tokens in pathauto to define your URL structure.

```
function MYMODULE_token_info() {
  // Because of http://drupal.org/node/691078, we just hack in our own
  // field-based tokens here for now (cough).
  // These tokens are only available for nodes of type MY_CONTENT_TYPE_WITH_LOCATION_FIELD
  $node['field_location_street'] = array(
    'name' => t("Location Street"),
    'description' => t('The street address that a location is located at.'),
  );
  $node['field_location_city'] = array(
    'name' => t("Location City"),
    'description' => t('The city that a location is in.'),
  );
  $node['field_location_province'] = array(
    'name' => t("Location Province"),
    'description' => t('The abbreviation for the province (State) that a location is in.'),
  );
  $node['field_location_province_name'] = array(
    'name' => t("Location Province Name"),
    'description' => t('The full name of the province (State) that a location is in.'),
  );
  $node['field_location_country'] = array(
    'name' => t("Location Country"),
    'description' => t('The country that a location is in.'),
  );
  $node['field_location_country_name'] = array(
    'name' => t("Location Country Name"),
    'description' => t('The full name of the country that a location is in.'),
  );
  $node['field_location_summary'] = array(
    'name' => t("Location Summary"),
    'description' => t('A parenthesized summary of the location (City, State).'),
  );
  return array(
    'tokens' => array('node' => $node),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    $location_field = array();
    if (($node->type == 'MY_CONTENT_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_location['und'][0]))) {
      $location_field = $node->field_location['und'][0];
    }
    if (($node->type == 'MY_CONTENT_TYPE_WITH_NODE_REF_TO_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_event_site['und'][0]))) {
      $location_nid = $node->field_event_site['und'][0]['nid'];
      $location_node = node_load($location_nid);
      if (isset($location_node->field_location['und'][0])) {
        $location_field = $location_node->field_location['und'][0];
      }
    }
    if (!empty($location_field)) {
      $location_field['summary'] = "(" . $location_field['city'] . ", " . $location_field['province'] . ")";
      foreach ($tokens as $name => $original) {
        if (substr($name,0,15) == 'field_location_') {
          // $name is always 'field_location_xxx', so key is 'xxx'.
          $key = substr($name, 15);
          if (isset($location_field[$key])) {
            $replacements[$original] = $location_field[$key];
          }
          else {
            $replacements[$original] = '';
          }
        }
      }
    }
  }
  return $replacements;
}

```
> 0 votes

---
Tags: entities, path-aliases, uri
---


# Question
Title: Views Calc always uses contextual filters of master display
I have many displays in the view.
One of them is a views calc table.
Contextual filters in the master display and in the views calc display are different.
And when contextual filters differs from master views calc doesn't work correctly.
Views calc ignoges contextual filters of the current display and shows calculation results using contextual filters of master.

Has enybody noticed this issue?

# Answer
As temporary solution : I've deleted all contextual filters in the Master display and overrided them in other displays

But then i patched Views Cals module.

Views calc realy always executes "filter criterias" and "contextual filters" from default display. So before executing view we must set view in a needed display. It's very important! Here is the patch for it:

http://drupal.org/node/1868900#comment-7026538
> 0 votes

---
Tags: 7, views
---


# Question
Title: Show fields content node according to its taxonomy using views 3
I need to create a view block type and show only the title of my node and its image but they are related by their taxonomy.

The image is attached to the node.

The node has its taxonomy\_field field.

I have two taxonomy vocabularies: products, services.

The block will be placed on pages where have as URL: "taxonomy/term/tid" But these have their path URL alias, that is: " products/title-taxonomy " Then, the block is configured to only in scrambled URLs such as " products/\* "

When creating my view I have the following configurations:

Fields: \- Title \- field\_image

relationships: \- Content: Taxonomy terms on node \- Vocabulary: Products

Contextual Filter: \- Content: Has taxonomy term ID (with depth) \- Provide default value -\> Type: Taxonomy Term ID from URL -\> Load default filter from term page

But, when I activate the block in the content region does not show me any results. Change the setting of contextual filter by:

* Content: Has taxonomy term ID
* Provide default value -\> Type: PHP Code -\> return arg (2); This value would only take the url: taxonomy / term / tid that is covered by his alias and would return the tid value.

But I get an empty result. Even in the preview of the view, if I put a value directly, does not generate any results.

What is it I'm doing wrong? Or need some more configuration?

# Answer
If the title and image you are showing in the block are the same as the title and image of the displayed node, then you do not have to relate the block to the node through taxonomy.

Delete the relationship, and the contextual filter. Set up a contextual filter on Content:NID, and configure it to Provide default value -\> Node ID from URL.
> 0 votes

# Answer
OK, I do it!.. My solution is use the module Taxonomy Display for D7. Related a view with taxonomy page and It's work!
> 0 votes

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


# Question
Title: If one block has content do not show other block
I have a region in my `page.tpl.php` file called "seminars", and it has two blocks (views) assigned to it, one is called "view\_upcoming\_seminar" and the other is called "testimonials". The content shows up great for both blocks (views) in the region. What I'd like to do is only show "testimonials" if there is no content in "view\_upcoming\_seminar".

I'm just not sure what the best approach is, and any pointers in the right directions would be grand!

# Answer
Open the "Advanced" section on the "view\_upcoming\_seminar" View settings page, and add a "No results behavior" of type "Global: View area". Point it to your "testimonials" View.
> 2 votes

---
Tags: blocks
---


title: How do I make a clickable dropdown menu

text:
# Question
Title: How do I make a clickable dropdown menu
How do I make a clickable dropdown menu? I'm making a dropdown menu that allows the user to click the item they want. I would like then like that page appear automatically, or at least allow the person to click on the item and taken to the new page.

# Answer
> 1 votes
There are several modules that can accomplish this, eg Superfish and Nice Menus.

If you want to roll your own, the basic steps are

* Edit you menu items (admin/structure/menu/manage/menu-foo-menu) so that they are always expanded. This will result in all menu items always being available, instead of only available in the active/sibling hierarchy.
* Write some CSS and JS to get the menu behavior that you want. With the way the nested menus are built in Drupal, you should be able to achieve a CSS only solution. You can either do this with a custom module, or add it to your theme.

The CSS and JS involved with this is beyond the scope of this site, but there are lots of resources on the net to help you out.

---
Tags: navigation
---


title: Know when an order has been paid

text:
# Question
Title: Know when an order has been paid
I need to export some order data to a CSV file. One field is the date (d-m-Y) when the order has been paid. I have search in hook\_commerce\_\*, in the database, but I have not find anything that can help me. Is this data saved in the database, or I need to create a rule that saves this information when the order is payed in full the first time?

# Answer
I needed to do this in the past. I exported with a View, and used a *Representative payment transaction* relationship, using *Commerce Payment Transaction: Status* as the representative sort criteria. Then I just added the *Commerce Payment Transaction: Created date* field. Assuming that the entire payment is done in one go, I think this method's sound.
> 4 votes

# Answer
Yes this information is stored in the database.

Look at the database for a table called `commerce_payment_transaction`. Here it is stored the transaction information of the attempted payments. The column `status` will tell you if the payment was successfull and in the `created` field you have the payment date (in POSIX time).

That said, using Views and Views data export could be another solution.
> 1 votes

---
Tags: 7, commerce
---


title: Ubercart Roles: Expire to another role

text:
# Question
Title: Ubercart Roles: Expire to another role
I use Ubercart Roles to manage access to parts of a member site, but I want to be able to keep track of users who's role has expired.

We have generic authenticated users, who are able to make purchases, but are unable to access member pages, and we have a 'member' role, that expires at the end of the year. At role expiration, I would like to have the 'member' role removed and an 'expired' role added. If they renew their membership from 'expired', I would like their role to go back to 'member'.

Is there a module that will help me with this?

# Answer
> 3 votes
Using Ubercart Roles, there is an event defined to trigger on sending the user a notification that their role has expired. You can use that event to trigger a rule, or you can define a role expiration event if you wish to tie it to a discrete event rather than the sending of an email. There is a proposed patch for Role Expire which creates a Rules event upon role expiration that you might use as a model.

Once you have created your rule, it is a simple action to assign a role (Add user role action) to the expiration:user.

---
Tags: 6, ubercart, users
---


title: Tokens to change a block's visibility

text:
# Question
Title: Tokens to change a block's visibility
I am trying to make a block visible only to pages whose URL matches user/\[current-user:uid\]/downloads, but I don't get anywhere.

Do you have any idea on how to achieve this?

# Answer
> 0 votes
Fairly sure you can't do this from within the Blocks interface, but would be delighted learn otherwise.

A strategy to try would be to create a Views block that will display or not as required. A View over Users with a Contextual Filter that takes the Raw Value from URL, picking out a given path component, would be a start. You can then filter the view by User: Active.

If that all works out then your View will show. You can then get the content you want for your block by using a Rewrite of User: name field and, perhaps also, using Global: Text area in the header. (Well, you might be able to get the content this way. Depends on what's needed in the block.)

When you add the View block, you'll do something such as user/\*/downloads, but the block will show depending on current user matching the contextual filter.

---
Tags: blocks
---


# Question
Title: Position Block Below Content but Above Editor
I have created a block for a horizontal ad. I positioned it in the Content region and as you know I can display it either above the content or below everything. However, I would like it positioned above the editor (or comments area), not above it all.

I have found this pots but I am using an Omega-based theme and I see under the all/themes/omega/templates folder that there are "region.tpl" files so I assume here is where I add it, not in a node.tpl.php file.

# Answer
> 0 votes
Omega based themes still allow for custom regions and various \*.tpl.php files. There is probably a `node.tpl.php` theme file in the base theme thats inherited by the subtheme your using.

The code doesnt go in the tpl.php file it goes in the preprocess function:

> How to display block in node above comments. What i have tried is: create region - regions\[above\_comments\] = Above comments after in template.php i have added this to THEME\_preprocess\_node

You then output the correct `block` within the specific `region` of the theme. In the linked page they created a region called `Above comments` in their theme. They set a block to that region using the Blocks Admin UI and rendered it using `block_get_blocks_by_region` using the theme preprocess function.

---
Tags: blocks, theming
---


title: hide published node's field?

text:
# Question
Title: hide published node's field?
I want to hide one of a node's field when the node was published. I copied and renamed the node.tpl.php as node--app.tpl.php cause the node's content type's machine name is app.

I tested it by add the code at the beginning of the node--app.tpl.php file. yeah it works.

```
<?php print $node->field__iap_dl['und'][0]['url']; ?>

```

In order to hide the field I added one line in the existing code.

```
<div class="content clearfix"<?php print $content_attributes; ?>>

<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  hide($content['field__ipa_dl']);    // I added!
  print render($content);
?>
</div>

```

This time it didn't work. What's wrong? I am newbie to code the Drupal.

# Answer
> 0 votes
You did not tell it to hide `$node->field__iap_dl['und'][0]['url']`.

The field probably did not show up in the rendered content, but it will still appear if you tell the template to print the information directly from the node object.

The simplest way to hide a field is to go to /admin/structure/types and under manage fields for the content type, mark the field as hidden.

EDIT:

Is this a cut and paste of your code? If so the fields names are different. **field\__iap\_dl** is not the same as **field\__ipa\_dl**.

---
Tags: entities, theming
---


# Question
Title: Reject Form Submissions with URL in them
I have a client who is using Drupal and has an email contact form. The problem is they are getting spam sent through the form daily.

I have tried the Re-captcha plugin, captcha plugin, Anti-spam (Askimat), and Honeypot plugins.

The offenders are using programs like XRumer which is capable of solving captcha's and none of these plugins have been able to stop the bots.

So I am asking others if they have any advice on how to stop these contact form spam submissions?

Since this particular form shouldn't have a legitimate reason for a URL in the body section, possibly I could detect URL's and then return an error if they are present when a form is submitted?

# Answer
It is possible to create contact forms using either the Webform module, or the Entityforms module.

The beauty of the latter is the ability to attach fields, and to validate those fields with the Field Validation module, which offers a wide range of validation options.

There is a Webform Validation module for use with Webforms, but I think you will find Entityforms with Field validation to be a little more flexible and, perhaps, easier to use.

Either one should let you scan text for say "\<a href=" or any other undesireable word or phrase (blacklist matching) or constructs using regular expressions, if you are so inclined.
> 3 votes

# Answer
I am not familiar with what XRumer can and can't do, but it would surprise me if it had the answer to all possible questions. That in mind I would suggest Captcha Riddler which I find works great.
> 1 votes

# Answer
A very simple alternative with custom code (I personally think installing a bunch of modules for such a simple task is massive overkill):

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'my_form_id') {
     $form['#validate'][] = 'MYMODULE_form_link_removal_validation';
   }
}

function MYMODULE_form_link_removal_validation($form, &$form_state) {
  // Basic regex for anchor tags
  $regex = '/<a[^>]*>/i';

  if (preg_match($regex, $form_state['values']['body_field'])) {
    form_set_error('body', t('Links are not allowed in this field.'));
  }
}

```

You could take that a bit further if you wanted and implement a proper filter for it (see `hook_filter_info()`), and also attempt to match links outside of anchors if you have the 'Convert URLs to links' filter turned on. The mechanism is the same, the string matching method would just need to be replaced accordingly.
> 1 votes

# Answer
Not too sure about checking for a URL but there is a page on drupal.org that talks about spam prevention on the contact form - Spam Prevention. It mentions a few modules that you haven't tried yet.

There is also a slew of spam prevention modules on the following drupal.org page - spam prevention drupal wiki page
> 0 votes

# Answer
Here is the full module code(D6) which blocks url submissions within Webforms. If you want D7 version then please let me know.

Even if you block url submissions, Bots would still try to post! I've one D6 based site and all spammers from around the world try to spam it whatever way, with or without url.
> 0 votes

---
Tags: advertising
---


# Question
Title: How to add frontend form using custom content type?
I new to Drupal and I created a custom content type which has few fields, like donation name, value, size, etc.

I want to add these fields as a form for user which they can fill in the frontend. I want to know there are existing for this task or it can be done through core module

# Answer
This is usually done by giving the user permission to add the content type and presenting them with the /node/add/{content\_type} page, letting them create their own page content.
> 1 votes

# Answer
An ideal solution for your problem would be to use the webform module, which is used in similar scenarios and has many features out of the box.

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

It also has a very good documentation which will help you to get started.
> 1 votes

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


# Question
Title: Render Panels Overridden user profile template
I have overridden the user profile template using `Panels` module and want to render this overridden user profile in one of my custom module.

Actually I wanted to show "About Author", tab besides the "View" tab of article, which when clicked, will show overridden user profile.

For that I have created menu entry as follows:

```
function custom_menu() {
   $items = array();

    $items['node/%node/author'] = array(
        'title' => 'About Author',
        'page callback' => 'get_node_author',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

```

My function is as follows:

```
function get_node_author($node = NULL) {
    $account = user_load($node->uid);
    $account_view = user_view($account);
    return drupal_render($account_view);
}

```

But it is loading user profile in normal format and not the one which is customized using panels.

Any suggestion how can I achieve this?

# Answer
I suggest you don't create a menu hook at all.

Just implement your desired layout in a custom panels page instead, and you can control the menu from there.
> 2 votes

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


title: How to print fields in node.tpl.php?

text:
# Question
Title: How to print fields in node.tpl.php?
I need to print individual fields from the `$content` variable in `node.tpl.php` file in separate `div` tags. How do I do that and how do I find out what the field's names are?

# Answer
Try this

`<?php print render($content['your_field_name']); ?>` this will print that field value .
> 22 votes

# Answer
enable Devel module and in node-{content-type}.tpl.php

```
    <?php dsm($node); ?>
    <?php dsm($content); ?>

```

you can see all $node fields and content fields
> 6 votes

# Answer
You can use the Devel module and use dpm($content) or kpr($content) functions in your node.tpl file. From there you can see all the names and render them the way you want.
> 3 votes

# Answer
I use the Devel Module，to find the field name. It's very useful.
> 0 votes

# Answer
The best way to find the fields available are :

```
<?php
  print render($content);
 ?>

```

in your tpl file. This would display the list of fields available. You can remove these lines later. Then, to print your individual fields you can just do:

```
print render($content['field_blog_pic']); or

 print $title

```

depending on your fields (user pictures, image fields, normal text and so on).
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to use _user_mail_notify with a defined language
as the title say, I would like to know how to use `_user_mail_notify` with a specified language.

According to the documentation the third parameter should be the one that override user\_preferred\_language() but when I specify it the language used is always the one returned by language\_default().

My code is pretty simple:

```
_user_mail_notify($op, $account, $mail_lang);

```

Where:

`$op` is `'register_admin_created'` as the account is created programmatically.
`$account` is the return value of user\_save
`$mail_lang` is an object selected from the array returned by language\_list('enabled') (as I understood it should be).

I don't know if I'm using it wrong or there is a bug in the function, anyone used it with a custom language and can help me understand?

Thanks you.

# Answer
> 3 votes
I finally understood and overcome the issue, in order to send emails in a different (enabled) language multilingual features must be enabled for the emails.

To enable the multilingual features there are just few steps:

1. The module "User mail translation" has to be enabled
2. From the Variable configuration (admin/config/regional/i18n/variable) you have to select the tab "User emails" and then check the email types you want available in a different language
3. From the account setting page (admin/config/people/accounts) then you select the language (in the very first box of the page) and add the translation for the related email templates (just scroll down)

After this 3 steps you will be able to send emails in all the enabled (and translated) languages in your site.

---
Tags: 7, users, emails
---


# Question
Title: PDOException: SQLSTATE[42S02] when changing password using Drupal Commons 7
I'm new in using Drupal Commons 7. I've been trying to register a user in the membership site that I'm making but this comes out whenever the user tries to change his password:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table '\[name\].oauth\_common\_consumer' doesn't exist: SELECT c.csid AS csid, c.consumer\_key AS consumer\_key, c.secret AS secret, c.configuration AS configuration, pc.created AS created, pc.changed AS changed, pc.uid AS uid, pc.name AS name, pc.context AS context, pc.callback\_url AS callback\_url FROM {oauth\_common\_consumer} c LEFT OUTER JOIN {oauth\_common\_provider\_consumer} pc ON pc.csid = c.csid WHERE (c.csid = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> ) in DrupalOAuthConsumer::loadById() (line 173 of /home4/\[name\]/public\_html/profiles/commons/modules/contrib/oauth/includes/DrupalOAuthConsumer.inc).

How can this be fixed?

# Answer
> 1 votes
This indicates a database table is missing. Given that the error happens in the oauth module itself, I would assume the error is not caused by incompatible modules working together. I can think of three possible causes:

1. You need to clear the caches.
Whenever you have a problem like this in Drupal, you should try clearing the caches. This can be done by going to *Administer \> Site Configuration \> Performance* on your site.
2. You need to run some database updates.
When you upgrade modules, they sometime needs to run some update code which can, for instance, add new tables or change table definitions. This can be done by going to `/update.php` on your site.
3. There was an error when installing this module.
If neither of the possibilities above work, you might want to try to disable this module, and re-enable it to see if there is any problem during installation.
**Warning**: this will probably require you to disable other modules, and might cause a loss of data. Try this on a copy of the site.

---
Tags: users, 7
---


# Question
Title: Exporting custom configurations from Drupal
After installing a Drupal7 site, I have made several configurations/customizations over time. Now I would like to export them somehow, in order to load them to another site. But the problem is that I don't remember exactly what I have done. The Features module does not help because you have to tell it exactly what to export, but I don't remember all the changes.

I know that this is a difficult problem on Drupal7, which is expected to be solved on Drupal8. But I am asking just in case that somebody knows any tricks that can help to solve it on Drupal7.

# Answer
Check out the Configuration Management module.

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.

It's kind of a backport of features worked towards in the Drupal 8 Config Management Initiative. You basically trac certain elements of configuration on your site (this bit is *relatively* similar to Features), and then it tells you when there are differences between what is stored in the filesystem and what is stored in the database (referred to as ActiveStore and DataStore). These config files can then be versioned and deployed.

As an added bonus, of you install the Diff module you can see what's actually been changed with regards to ActiveStore vs DataStore :-)

***tl;dr***

The Configuration Management module attempts to bring Drupal 8 style configuration management to Drupal 7.
> 1 votes

# Answer
You can features module. So you can create a feature of several configuration and can use in other installation.

**Sorry I missed the features part in question, which you already know.**

*I think features is the best solution for exporting configurations. other than features nothing is there for exporting all configurations without telling what to export.*
> 2 votes

# Answer
Check out the features\_orphan module. AFAIK it still only works with features 7.x-1.x, not 2.x.

This will show you all of the config which doesn't currently live in features. Combine this with the "drush fd \[feature-name\]" you should be able to see all of your changes.

One thing to keep in mind is that it is very rare that you will want to export **all** of the config from one site and use it on another. There are some variables such as site\_key, cron\_\* etc which you won't want in the export.
> 1 votes

---
Tags: importing-exporting, configuration
---


title: how to Insert form data in table

text:
# Question
Title: how to Insert form data in table
i have an enquiry form and submitting the form using jquery/ajax method.

```
$.ajax({
          url:enquiry.php

```

I am able to insert records into database table using php mysql\_query. When i use db\_query in "enquiry.php" page, i am getting errors.

```
   Call to undefined function db_query()

```

i want to know how to use db\_query to insert records in database table.

# Answer
For that function to be available from outside Drupal, you need to first bootstrap Drupal. This means that, with Drupal 7, the first lines of enquiry.php needs to be the following ones.

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

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

```

I assume the enquiry.php file is in the same directory containing the index.php file that comes with Drupal.

I would rather suggest you to read the following questions, though:
> 2 votes

# Answer
This function is defined in includes/database.inc file.

You have to include `database.inc` in your file to get db\_query() working.

```
<?php include(“includes/database.inc”); ?>

```

However if you are trying to access drupal database from a `enquiry.php` file then all you need to do is to include following lines at the top of your file.

```
require_once ‘./includes/bootstrap.inc’;
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 0 votes

---
Tags: database
---


# Question
Title: Stripping the wrappers in a custom field d7
I have a custom field in d7 and I output it as

```
 <?php print render ($content['field_product_image']);

```

The problem is it wraps around a whole load of stuff. How can I get in and edit this html?

I suspect somewhere in the field templates or using the api. I can live with the bloated html if I could get rid of the title on the a tag (title="Sample 1")

```
<span class="image-wrapper"><a title="Sample 1" href="#1" rel="history" class="advance-link">
                    <div class="field field-name-field-product-image field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img typeof="foaf:Image" src="http://extranet.shy-uk.com/sites/extranet.shy-uk.com/files/look-detail_0.jpg" width="620" height="320" alt=""></div></div></div></a></span>

```

# Answer
inspect the field with `dpm($node);` or `dpm($content['field_product_image']` you will see the array structure which should be something like:

```
$node->field_product_image['und'][0]['fid']
$node->field_product_image['und'][0]['title']
$node->field_product_image['und'][0]['uri']
$node->field_product_image['und'][0]['filename']
$node->field_product_image['und'][0]['width']
$node->field_product_image['und'][0]['height']

```

to actually render the uri (something like public://filename.extension) you will need to to this:

```
$filename = $node->field_product_image['und'][0]['filename'];
$image_uri = file_build_uri($filename);
// url
$url = image_style_url('my style', $image_uri);
// html
print theme('image_style', array('style_name' => 'my style', 'path' => $image_uri));

```

update (shorter, one needless function call removed):

```
// url
$url = image_style_url('my style', $node->field_product_image['und'][0]['uri']);
// html
print theme('image_style', array('style_name' => 'my style', 'path' => $image_uri));

```
> 0 votes

# Answer
You can override field.tpl.php and its derivatives if you want to code it manually.

Or the Fences module might do the trick:

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

It lets you control the base markup for each field through the UI - a must have for any project these days in my opinion :)
> 0 votes

---
Tags: entities, theming
---


# Question
Title: Select entity to display using drop down list
My problem is that I want to add a drop down list to a node that selects an entity from that node based on its name, and display it. I am wondering if there is a module that does that; if there isn't, what the best approach is.

So far, I can only think of creating a custom node template to display the entities using JavaScript.

Unless I am mistaken, the Entity reference module won't work in my case; if it does, please clarify.

I have 4 tables in a single node; each table represents a week in a month. I want just a simple drop down list to select which week to display, and display that week's table.

# Answer
seems no one can answer so I did what I first thought of for the sake of documentation

I added this to my node template node--NODENAME.tpl.php

```
<?php drupal_add_js('sites/all/themes/MYTHEME/scripts/scripts.js');?>
    <select id='showmethemoney'>
        <option selected="selected" value="field-name-field-week1">week1</option>
        <option value="field-name-field-week2">week2</option>
        <option value="field-name-field-week3">week3</option>
        <option value="field-name-field-week4">week4</option>
    </select>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content['field_week1']);
      print render($content['field_week2']);
      print render($content['field_week3']);
      print render($content['field_week4']);
      print render($content);
    ?>

```

and Created a js file "sites/all/themes/MYTHEME/scripts/scripts.js" with the following code :

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

 $(function() {
        $('#showmethemoney').change(function(){
            $('.field-type-text').hide();
            $('.' + $(this).val()).show();
        })
     .change();
    });

}
};
}(jQuery));

```

this will show the selected field by default and will display the field I want from the select list

thanks for your time
> 0 votes

# Answer
Checkout the Entity reference module.

> Provides a field type that can reference arbitrary entities.
> 3 votes

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


# Question
Title: Do I need all drupal core history in my own repository
I decided to update core via git, mostly by following the approach explained here.

I did this (in my local repo, dev branch):

```
git remote add core git://drupalcode.org/project/drupal.git
git fetch core
git merge 7.21
(resolved few conflicts)
git commit --amend
drush updatedb

```

I did this for the sake of making it easy to update core in the future, as proposed:

```
git fetch core
git merge [new commit hash]

```
* Am I adding too much to my project by fetching all core history, or is this needed? I am interested only in updating core in my existing project.
* If so, can I get rid of the core history?
* Can I in next core update fetch only by tag?

# Answer
Drupal.org suggests a similar approach. But, I'm not sure I understand the need to keep core's history under your own repo either. Or any code you yourself didn't create or amend.

Why not just have your repo at /sites/? And have your ignore file leave out anything you haven't touched, including unmodified modules from drupal.org (and all the stuff in /sites/default/files/). Then you're workflow could be to use drush to update core, modules and themes and use git for all your own code. Use `drush rsync` for files when working between local, dev, stage and production.

Side note: I'm glad to see this question here because this is something I've been wondering myself and though I don't use the approach I've just suggested, I'm thinking about it.
> 1 votes

---
Tags: version-control
---


# Question
Title: How does the tmp folder work? It stores lots of junk files and takes space
My tmp folder is set to /sites/default/files/tmp/ and I checked what's inside and for example there is folder inside called /update-cache-b2903cc4/ it keeps all modules in .zip that I installed via 'Install from a URL'. So why are those modules .zip files are kept there in tmp folder, isn't it a waste of storage? I don't really like it when the site is full of unnecessary files.

Am I supposed to delete these by myself all the time?

# Answer
> 21 votes
## What does tmp mean?

Tmp is an abbreviation of temporary. So the tmp folder is a folder intended for temporary files. Every operating system uses such a folder, and in facts needs it. So does Drupal. Drupal by default attempts to store files in your operating system's tmp folder. On Linux this is `/tmp`, on Windows `C:\Windows\Temp`. You can check and change this setting in `Configuration > Media > File System`. If your temporary directory is set to one of these standard paths, you should assume it is not only Drupal's files, but files of the operating system and several other programs (Apache sessions, Drush downloads, installation packages). If it is on a custom path, or in the case of the OP: `/sites/default/files/tmp/` (Drupal's fallback path) it should contain only Drupal files.

## So what kind of files does Drupal store there?

In general Drupal stores all uploaded files in the temporary folder first. If something goes wrong (eg. the connection with the client is interrupted) there is a corrupted file on the server. Keeping these files in a temporary folder and only moving them after the whole file was transferred, ensures there will be no damaged or unneeded files in your public files directory `sites/default/files`.

This also includes modules and translation downloads, some js files (probably used in aggregation) and several other files.

There is no real list of all files Drupal stores in tmp, because contributed modules might choose to store a file there as well. Possible use cases for this could be file generation on demand (eg. a module that packages a custom selection of files into a zip file and offers it as download. It is unlikely the same file will be used more than once and there is no real benefit in storing it).

## Can I safely remove the files?

Well yes and no... The idea of temporary files is that they are, well... temporary. They are generally used directly after they are created and might no longer be needed. But since all programs can write to tmp, it is a reasonable assumption not all programmers played by the rules, or some files might in fact still be in use.

## Should I remove the files?

Drupal performs several cleanups on its own during cron runs (assuming cron is set up and working). Uploaded files that were not saved permanently will be removed during system\_cron(). Old modules downloads are handled by update\_delete\_file\_if\_stale() (via update\_clear\_update\_disk\_cache() and update\_cron()). These cleanups are set to clean up files older than DRUPAL\_MAXIMUM\_TEMP\_FILE\_AGE (6 hours), but the actual time depends on the cron interval. (If cron only runs every 12 hours, it can take up to 12 hours before the files are removed).

In most cases there should be no need to remove the files manually. If in some cases cron doesn't remove (all) files, you might attempt to remove them by hand. But make a backup first!

If your folder is shared with your operating system's folder, you might want to use your operating system's tools for it (Windows users can clean the temporary files with the `Disk Cleanup` tool. (Some Linux distributions clean the folder during system reboot, some don't.)

When the tmp folder is on a custom (non-operating system) path, as is the case with the OP, it should be relatively save to empty the folder by hand. Make sure your webserver (Apache, Nginx) is stopped, so no user of cron task will be touching the files. Then delete the stale files (older than 6 hours) manually.

## Conclusion

If your system is setup properly and cron is working, there should be no need to clean these files, as they are removed automatically. If it doesn't happen, you can remove them manually, but keep above conditions in mind. It might still go wrong, so always make a backup!

---
Tags: 7, files
---


# Question
Title: own custom module in which the value from the submitted form gives 0
In a custom module, I have created a form with a text-field and a submit button.

The problem is that I can't get Drupal to save my value, and the validation function is also not called.

```
function subscription_perm() {
  return array('access subscription');
}

function subscription_menu() {
  $items = array();
  $items['generate/subscription'] = array(
    'title' => 'Subscription Form',
    'description' => 'A form to generate the subscriptions',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('subscription_gen_form'),
    'access arguments'   => array('subscription generation for the members'),
);
  return $items;
}

function subscription_gen_form() {
  $form['txtSubcription'] = array(
    '#type' => 'textfield',
    '#title' => 'Subscription Generation',
    '#value' => 500,
    '#size' => 10,
    '#required' => TRUE,
  );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    '#submit' => array('subscription_gen_form_submit'),
  );
  return $form;
}

function subscription_gen_form_validate($form, &$form_state) {
  if($form_state['values']['txtSubscription'] < 500) {
    form_set_error('txtSubscription', t('pls enter the correct subscription amt'));
  }
}

function subscription_gen_form_submit($form, &$form_state) {
  db_query("INSERT INTO {Ex}(Amt) VALUES (%d)", $form_state['values']['txtSubscription']);
  drupal_set_message("the value have been submitted in the db");
}

```

# Answer
> 1 votes
The validation not happen due to spelling mistake in the textfield name for Subscription Generation. Please check with below one

```
$form['txtSubscription'] = array(

```

# Answer
> 0 votes
It is:

```
#default_value

```

not value that sets an initial value for a field. #value creates a form element that never displayed - similar to hidden, but not displayed in the form at all. If you just want to pass through values then #type = 'value' is what you want.

```
// Record the serial number to identify this replicant.
$form['meetingclone']['meetingclone_serial'] = array(
    '#type' => 'value',
    '#value' => _meetingclone_find_template_node()->nid . '_' . time(),
);

```

---
Tags: forms
---


# Question
Title: Get book bid to display at search results page
I'm trying to tweak my search results template to include the book root title at the bottom of every search results snippet. I have several books with very similar titles and content and i'd like to be able to print title of the book below each search result snippet so users know what they're going to get when they click search result.

I tried simply print $node-\>book\['bid'\] but it didn't print any result. I think it's because i have to somehow get the bid of a snippet and i'm getting bid of search results page which has no bid.

Am i right? And how i do that? I'm using Custom Search module to display my search results.

# Answer
The book id `bid` is nothing more then the node id `nid` of the parent. Therefor if you have the bid, you still need to extract the title from the parent node.

```
$search_hit = $variables['result']['node']->nid; // The node id of the search result item
$node = node_load($search_hit); // Load the whole node whose search result we got
$parent_id = $node->book['bid']; // Extract the parent from the found node

$node2 = node_load($parent_id); // Load the parent node.
echo $node2->title; // This is the parent title.

```
> 0 votes

---
Tags: search, nodes
---


# Question
Title: Restrict access to text formats for certain role
For every user with role `company manager` i have made tab `My company`(in user profile) where user can see `node_edit` of their company(node). And i need to set default format to `plain-text` and hide text-format drop down list only for this role. Ofc. i can do this for every user, i can change settings in my content type field settings, but this way the other users will not see it too.

Any suggestions? how can i achieve this?

# Answer
> 0 votes
This can be achieved by some coding. If it is okay to make a custom module then it can be done via hook\_form\_alter(&$form, &$form\_state, $form\_id)

In this hook get a debug statement to get the form id for your node edit page. Now in that page you need to get the type of node being edited. So there are 3 things to look for.

1. Get the form\_id for the node edit page. Then use this in a switch-case statement to perform your logic.
2. Then get the Node type that is being edited, from the URL. So if you are in a edit page then the URL will be like, http://example.com/node/14/edit. For arg(2) you will get the node id. Perform a node\_load and call node\_type\_get\_name($node) or just a simple database query to node table by node id will do it for you.
3. Check for the User role and decide to show/hide the select box.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    switch($form_id) {
       case "node-edit_form" : //may differ as I am only giving a demo
         //Add your logic
         $nid = arg(2); //Add some isset check will be good and filter_xss() for security purpose.
         $node_type = db_select('node', 'n')->fields('n', array('type'))->condition('nid', $nid, '=')->execute()->fetchObject();
         if($node_type->type == 'your_needed_type') {
              if(array_key_exists('company manager', $user->roles)) {
                  $form['#after_build'][] = 'mymodule_your_needed_type_node_form_after_build';
              }
         }
       break;
    }
}

function mymodule_your_needed_type_node_form_after_build($form) {
    // We want this on a specific field
    $form[LANGUAGE_NONE]['0']['format']['#access'] = FALSE;
    return $form;
}

```

I think this will solve the issue for you. You can do some R&D and make it more efficient like to add more checks.

# Answer
> 1 votes
Alternatively, you can use the Better Formats module, it gives a lot of possibilities to you to control text format selection.

# Answer
> 1 votes
Instead of coding, this can be achieved from admin configuration in drupal 7.

Go to

> Configurations \> Content Authoring \> Text formats

at this page, you can set restriction against your roles.

# Answer
> 0 votes
A simple but relevant sledgehammer approach would be to revoke permission to use anything but the `plain-text` format, using user\_role\_revoke\_permissions. (Similarly, if you want to *add* permissions to use a given text format for a given role, use user\_role\_grant\_permissions.)

```
user_role_revoke_permissions(DRUPAL_AUTHENTICATED_RID,
   array(... 'use text format filtered_html', ...));

```

---
Tags: 7, nodes, input-formats
---


# Question
Title: How to force Drupal search.module find "111-222" page by searching "111 222"?
How to force Drupal search.module find "111-222" page by searching request "111 222" ? For instance I have page example.com/111-222 about something, named 111-222 How to force Drupal to think that minus "-" and space is the same?

P.S. Famous search.module code modifications for partial search ( $query2 = substr(str\_repeat("i.word LIKE '%%%s%%' OR ", count($arguments2)), 0, -4); etc) is already applied.

thank you.

# Answer
> 1 votes
Looking at the API for search, it would seem that hook\_search\_preprocess will allow you to alter the way keywords are extracted, something like this:

```
function mymodule_search_preprocess($text) {
  return preg_replace('/(\d+)-(\d+)/', '$1 $2', $text);
}

```

I haven't tested this code, it's purely meant as a sample. It assumes your "words" are all digits as per the question.

# Answer
> 0 votes
The solr module provides an interface to altering the query. Switch to this search engine and create this in an otherwise blank module - called solrmods in this case:

```
function solrmods_apachesolr_modify_query(&$query, &$params, $caller) {
  $pattern = '/([^\s])-/';
  $replacement = '${1} ';
  $keys_escape_hyphen = preg_replace($pattern, $replacement, $query->get_keys());
  $query->set_keys($keys_escape_hyphen);
}

```

Be careful that Solr is probably set to using dismax query parser and '-' may mean exclude this from the query. This is just to be aware of this as the drupal solr module assumes this and changing it will probably just confuse it. There are other options in solr - you can filter characters there too using java. http://wiki.apache.org/solr/SolrQuerySyntax#Other\_built-in\_useful\_query\_parsers

---
Tags: search
---


title: Drupal chat slowdown my application

text:
# Question
Title: Drupal chat slowdown my application
I am using Drupalchat for my application. The issue is that my application getting very much slow down after put this chat system. I think the problem will be due to Ajax, it's keep on polling to the server for frequently to check the chat messages(incoming or outgoing). How to fix this issue to fasten my application ?

Also I am curious about how the facebook and gmail chat systems are working in general?

# Answer
> 3 votes
AJAX chats are pretty resource hungry by nature when running on Apache, so there are no easy configuration switches that will instantly give you better performance, I'm afraid.

The big difference between chat implementations is that GMail and Facebook uses a different backend, more suitable for AJAX polling / push. The node.js backend for Drupalchat might be able to help you in that regard. If I were writing my own chat from scratch, I'd probably try out http://www.ape-project.org/ which seems to be pretty good featurewise.

# Answer
> 0 votes
The problem with the drupal chat application is the client-side javascript. With a 100+ chatters, it slows down terribly and causes a very poor user experience. We tried this even using their paid service- but it just couldn't keep up.

# Answer
> 0 votes
The paid service of DrupalChat module has been updated to fix this issue. Earlier if you had high number of concurrent users, then the online chat list used to fluctuate a lot causing client side issue as browsers couldn't keep up with such high rate of data flow. This has been now been fixed by updating online user list continually instead of instantaneously. Please do give it a try now. Thanks!

---
Tags: 6
---


# Question
Title: Setting upper limit on user profile picture
I am not finding any option to set upper limit on user profile picture. Currently user can upload file of any size. I want to prevent this scenario and allow user to upload his picture of maximum 2Mb or other.

How can set upper limit on profile picture?

# Answer
You'll find it here: admin/config/people/accounts
> 1 votes

# Answer
yoursite.com/admin/config/people/accounts

it's set here, where you enable user pictures. don't forget to change your PHP file size limits to match.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to automatically add the permission "edit" on a node to a user who is not the author?
I'm in D6

I have a node type "Person" and a node type "Company"

Each node "Person" has :

* an unique field-node-reference to a node "Company"
* an unique field-user-reference (to a user)

So, several persons can belong to the same company

Use case :

* The person P1.1 (belongs to company C1) creates a node (article)

How to automaticly grant edit permission on this article to an other person (P1.2) who belongs to the same company (C1) ?

Thank you

# Answer
> 2 votes
Install Content Access and ACL, and then use Rules to add Person 1.2 as a person able to edit that content.

---

You may find this question helpful: Node access by role or user, what module(s) should I use?

> The Content Access module gives you role permissions at the content type and (optionally) node level. By default, node level permissions are disabled but you can enable it on a type-by-type basis.
>
> If you install ACL module, Content Access can give you per user permissions at the content type and node level.

---
Tags: 6, users
---


# Question
Title: D7 theme field items of a "List (text)" input as <UL>
In Drupal 7, I have a field for a custom node type that is a text list "List (text)" with a widget input type of "Check boxes/radio buttons". When displayed on the front-end the following HTML is generated:

```
<div class="field-items">
  <div class="field-item even">XHTML</div>
  <div class="field-item odd">CSS 3</div>
  <div class="field-item even">PHP</div>
</div>

```

How can I theme this output as an HTML `<UL>` instead? Something like this:

```
<ul>
  <li>XHTML</li>
  <li>CSS 3</li>
  <li>PHP</li>
</ul>

```

I should note that I'm overriding output using a `node--custom_type.tpl.php` file.

# Answer
> 4 votes
The "right" way of rendering a list, that is, one that interacts properly with all the other systems in Core is theme\_item\_list.

Code example:

```
// In this case, $result is a list of nodes returned from a database query.
$list = array();
$list['type'] = 'ul';
$list['title'] = 'List of nodes';
$list['attributes'] = array('class' => array('list-of-nodes'));
$list['items'] = array();
foreach($result as $record) {
  $list['items'][] = l($record->title, 'node/' . $record->nid);
}
$output = theme('item_list', $list);

```

This should be applicable in your node.tpl as well.

# Answer
> 1 votes
I can advise you to install Devel Themer (don't worry, you can install safely the dev version) and when you'll active you can navigate between elements and you'll have every information you need about theming.

So, active it and then select you element and check the candidate templates or/and candidate functions.

# Answer
> 1 votes
If you look into bartik template.php, you will find how to override taxonomy field output exactly to your expectation. This is applicable to any other field, the way you want either with UL, OL, DL, etc:

```
/**
 * Implements theme_field__field_type().
 */
function bartik_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '">' . $output . '</div>';

  return $output;
}

```

# Answer
> 0 votes
You can alternatively use the Text Formatter module which allows you to set the display of fields as either an unordered or ordered list - just like your original question's layout.

---
Tags: 7, theming
---


# Question
Title: How to generate a list of field items using the field item name programmatically in Drupal 7?
I need a way to generate a simple list of all the items in a particular field. The field name is field\_portfolio\_description, and I'm looking to simply loop through the results and output each item into an unordered list. For example:

```
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

```

Is there a way to do this programmatically without using a module like Views? I would also like to display the data in page.tpl.php not node.tpl.php. I tried checking out some Drupal functions like field\_info\_field but they weren't much help.

Update:

I've been working with the following function in my template.php file:

```
function blocks_preprocess_node(&$vars) {
  $node = $vars['node'];
  if ($node->type == 'portfolio') {
    $vars['description'] = $node->field_portfolio_description[LANGUAGE_NONE][0]['value'];
  }
}

```

However a quick var\_dump($description) where I'm trying to access the data brings up null. Am I on the right track?

edit: fixed typo

# Answer
> 1 votes
You're pretty much on the right track. Try something like:

```
function blocks_preprocess_node(&$vars) {
  $node = $vars['node'];
  if ($node->type == 'portfolio') {
    $portfolios = field_get_items('node', $node, 'field_portfolio_description');
    $items = array();
    foreach ($portfolios as $folio) {
      $items['data'] = $folio['value'];
    }
    $vars['description'] = theme('item_list', array('items' => $items));
  }
}

```

Adding stuff to nodes like this is maybe better in hook\_node\_view() in a custom Module. Because you're altering the node's content before its shown (and its adding derived content to the node, not just changing some markup at the theme layer).

**Code is untested and just Help. (but should mostly work)**

**Resources**

# Answer
> 0 votes
For reference, other answers for this question were posted here.

Alternatively, instead of editing your templates or the preprocess template.php file, you can use the tiny module Text Formatter which allows you to set the display of your fields to list items.

---
Tags: entities
---