# Question
Title: Create a Drupal 7 node by email and populate multiple fields
I'm trying to import an email from Salesforce to drive node creation in Drupal 7. I've got mailhandler/feeds set up to do most of the heavy lifting, but the one thing I can seem to figure out is how to populate 4 separate fields in the node from a single email.

I know I can map the subject line as one field and the body as another, but isn't there a simple way to parse the body content into three distinct fields?

# Answer
You can take a look at Feeds Tamper that allows you to modify data before it gets saved. Then create a custom plugin if needed.
> 2 votes

# Answer
Just in case you aren't already aware, there is a Salesforce module available. See drupal.org/project/salesforce.

The project page says it supports pulling Salesforce data into Drupal, so it may fit the bill.
> 0 votes

---
Tags: feeds, emails
---


# Question
Title: What is the nature of list variables provided by "Fetch content flagged by user"?
On my site (Drupal 7/Flag 2/Rules 2), users can flag taxonomy terms. I am attempting to write a rule that compares a list of taxonomy terms that I have created with each user's list of flagged terms.

I generated the list of flagged terms by using the **Fetch content flagged by user** action, which provides a variable of type *list of flag items*. However, I cannot directly compare this with my other variable, which has a type of *list of taxonomy terms*, because when I iterate through the list of flagged terms using a loop in Rules, the current item from the list of flagged terms is not recognized as a taxonomy term.

Is there a way to force Rules to recognize that the flagged item in question is in fact a taxonomy term? If not, what is the nature of the *list of flagged items* variable?

# Answer
> 1 votes
The action 'Fetch content flagged by user' definitely only returns node type content. I just tested it out and sent the items provided by that action **to a rule component which checked the content type**. It only sent nodes, not terms, though my user definitely had flagged terms...

Here's what I did to look into it.

1. Create a rule component: /admin/config/workflow/rules/components/
2. Make sure it's a rule or rule set component
3. I have mine accept 'any entity' as a parameter, because I want my original rule to supply it with the 'Fetch content flagged by user' list\_item, which this component can check
4. Eventually, you can have it accept a second parameter, which could be a list for it to add to, if the supplied entity is determined to be a type 'taxonomy term'... no need to do this yet, because we'll find out that none of the content passed is of this type. :-(
5. Once you've set the parameters, continue to your rule, and add a condition "**entity is of type**". Set this to 'taxonomy term' and then in an later iteration to 'node' to compare the results of each of these settings
6. I set the action based on the above test to be 'Show a message on the site' for now. This could have been something like 'add item to list' if the above test actually ever was true for terms.
7. Save the rule component, and go back to your original rule where you loop through the content tagged by the user. Add an action IN your loop, in which you call the above component (components appear at the very end of the list) and provide your current list item as the component's parameter.
8. You'll see that only flagged nodes are ever sent to the component, and never terms.

It seems that though flagging of terms was recently introduced in the Flag 2.0 module, the integration of that piece with rules is a little behind. :-(

Anyway, I hope the above helps shed some light in your situation. Let us know if you find a way around this. I've played around with it some more, and couldn't find a round-about way to get to what you need yet.

---
Tags: 7, taxonomy-terms, rules, flags
---


# Question
Title: How do I add a #process callback to a fieldset form element without overwriting the existing callbacks?
I am using the following code.

```
$form['my_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('My Title'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#access' => TRUE,
  '#process' => array('my_callback_function'),
);

```

If a fieldset is collapsible, it gets two callbacks at some point later.

```
form_process_fieldset | (Callback) form_process_fieldset();
ajax_process_form | (Callback) ajax_process_form();

```

They aren't added to the array with my callback function. If I look at the form array, there is only my callback; so, there is no collapse functionality.

I tried to avoid that by adding the callback in `hook_form_alter()`, but this is too early; the callback functions are still not there.

```
$form['my_fieldset']['#process'][] = 'my_callback_function'; //Not working eather

```

So where is the right place to add a `#process` callback to my own form element, so it gets added as last callback in the callback array, or at least is not destroying the callbacks implemented by this specific form element itself?

I do some calculations in the callback to set `#access = FALSE` for this fieldset under certain conditions. This works fine, but maybe this is the wrong way to do it.

The documentation on #process says:

> You will probably want to add to the existing array rather than writing over it, so don't follow this usage example exactly.

The documentation is not very helpful, I don't follow but there is no info how it is done right.

# Answer
> 5 votes
When you add a #process function to a form element, the default ones defined from hook\_element\_info() are not added. Using `hook_form_alter()` to add a #process function doesn't change the result, as `hook_form_alter()` is invoked before the default #process functions are added to the form element. This happens in form\_builder(), which uses the following code.

```
 // Use element defaults.
  if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
    // Overlay $info onto $element, retaining preexisting keys in $element.
    $element += $info;
    $element['#defaults_loaded'] = TRUE;
  }

```

If `$element['#process']` is already set, it doesn't get overriden by `$info['#process']`, which means the default functions are not added.

What you can do is invoke the default #process function from the one you define. If `mymodule_process_function()` is the function you add, it should contain code similar to the following one.

```
function mymodule_process_function($element, &$form_state) {
  if (isset($element['#type']) && ($info = element_info($element['#type'])) && isset($info['#process'])) {
    foreach ($info['#process'] as $process) {
      $process($element, $form_state);
    }
  }
  // ...
  return $element;
}

```

If the #process function is necessary in any form where a fieldset is present, then you can implement hook\_element\_info\_alter() to alter the information returned from system\_element\_info() about the fieldset form element.

```
  $types['fieldset'] = array(
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#value' => NULL,
    '#process' => array('form_process_fieldset', 'ajax_process_form'),
    '#pre_render' => array('form_pre_render_fieldset'),
    '#theme_wrappers' => array('fieldset'),
  );

```

The alternative that requires less code to be written is to add a #after\_build function to the fieldset. #after\_build functions are functions that are called after the #process ones, receive `$element`, and `&$form_state` as argument, and need to return `$element`. As `system_element_info()` doesn't set any #after\_build function, there is less code to execute.
For compatibility with any module that implement `hook_element_info_alter()`, and which could alter the fieldset definition, code similar to the one I shown before should be used also for the #after\_build property.

# Answer
> 2 votes
```
$fieldset_info = element_info('fieldset');
$fieldset_process = array_merge($fieldset_info['#process'], array('my_callback_function'));

$element['my_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('Name'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#process' => $fieldset_process,
);

```

---
Tags: 7, forms
---


# Question
Title: Which module for relationships in my particular case?
> **Possible Duplicate:**
> Relation vs. References vs. Entity Reference for managing node-reference-type relationships in D7

I want to figure out which module (and, probably, strategy) will fit my needs best in such a situation.

I've built a site, there are a lot of `piece`'s; each `piece` is either written or arranged by some `person` (or has both relations, composer and arranger); each `piece` can be a part of a `collection` (think of CD for performed `piece`'s or book for scores in PDF).

Here `piece`, `person`, `collection` are types (post types, or node types in Drupal I believe); `score`, `audio`, `video`, `text` etc are taxonomies (in `media` tree). And each `piece` can have any or all media taxonomies assigned. Also there are `genre` taxonomies.

A `person` can be a `conductor` (if `piece` presents some performance by `choir`), `soloist` etc.

So, `piece` can be connected with `person` by a named "role".

Below are some links to demonstrate what I actually want to have (or something like that); the site made with WordPress (using posts-to-posts plugin).

However, I don't like what I have: that was the first my attempt to make a site, I am nor a programmer neither designer... I don't know what I am. Anyway, I don't like that site in terms of code maintainability (I guess that's my fault, not WP's), so I'd like to rewrite it; and I'd like to design new theme and have better ("overall php+mysql") performance.

So, now **the question is**: which module should I try for this --- Entity Reference or Relations? Or any other? Can I hope I can get better performance (php+mysql)?

Please, take a look (everything in Ukraine, but there are buttons to google-translate, SORRY):

* here is Mykola Gobdych's page (conductor of Chamber Choir "Kyiv") --- below the photo there are links to other "views" (listen to pieces conducted by this `person`, listen to pieces performed by him, listen to his pieces --- either composed or arranged by --- etc)
* some `collection` of `piece`'s
* a `piece` --- please, note, here are two performances... actually these are two `piece`'s connected with "the same piece" relationship
* listen to choir view

I really would like to try to do something like this with Drupal; however, I am very new to drupal. And I am not a programmer .)

So, please help; I will appreciate any helpful information or suggestion.

Thanks!

# Answer
Both Entity Reference and Relation modules would do the work, but in your case I would suggest to go with Entity Reference module, since you don't have very complex relationships.
> 2 votes

---
Tags: views, theming, entities
---


# Question
Title: Drush on Amazon EC2 - Update local code while using a remote database
I am using Amazon's EC2 for my development environment and Pantheon for my deployment environment. Code changes are pushed to Pantheon using git. And this much works fine.

I would like to use drush to update the local code for my modules. I will then `git push origin master` to Pantheon.

However, on EC2 I cannot make this work. This was working on my old, dying laptop, but I cannot perceive a configuration difference.

```
[ec2-user@[redacted] rsda]$ drush pm-updatecode
Command pm-updatecode needs a higher bootstrap level to run - you will need to invoke drush from a more functional [error]
Drupal environment to run this command.
Command pm-updatecode needs the following modules installed/enabled to run: update.                                [error]
The drush command 'pm-updatecode' could not be executed.                                                           [error]
Drush was not able to start (bootstrap) the Drupal database.                                                       [error]
Hint: This may occur when Drush is trying to:
  * bootstrap a site that has not been installed or does not have a configured database. In this case you can select
another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a
jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
  Drupal version    : 7.19
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : dbserver.dev.[redacted].drush.in
  Database username : [redacted]
  Database name     : pantheon
  Default theme     : garland
  Administration theme: garland
  PHP configuration : /etc/php.ini
  Drush version     : 5.8
  Drush configuration:
  Drush alias files : /home/ec2-user/.drush/pantheon.aliases.drushrc.php
  Drupal root       : /home/ec2-user/code/pantheon/rsda
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

[ec2-user@[redacted] rsda]$

```

I could use the drush alias, but I don't want to make changes to the remote filesystem.

```
[ec2-user@[redacted] rsda]$ drush @pantheon.[redacted].dev status
 Drupal version         :  7.19
 Site URI               :  dev.[redacted].gotpantheon.com
 Database driver        :  mysql
 Database hostname      :  10.181.132.28
 Database username      :  [redacted]
 Database name          :  pantheon
 Database               :  Connected
 Drupal bootstrap       :  Successful
 Drupal user            :  Anonymous
 Default theme          :  at_codex
 Administration theme   :  seven
 PHP configuration      :  /srv/bindings/[redacted]/php53
                           .ini
                           /srv/bindings/[redacted]/php53
                           .ini
 Drush version          :  5.1
 Drush configuration    :  /srv/bindings/[redacted]/drush
                           rc.php
 Drupal root            :  .
 Site path              :  sites/default
 File directory path    :  sites/default/files
 Private file           :  sites/default/files/private
 directory path

[ec2-user@[redacted] rsda]$

```

So it's possible to connect to the remote database--no firewall or DNS problem. The update module is enabled. Also, the referenced d.o issue applies to local databases, not remote ones.

For reference, here is the relevant part of my sites/default/settings.php:

```
 $databases['default']['default'] = array(
   'driver' => 'mysql',
   'database' => 'pantheon',
   'username' => [redacted],
   'password' => [redacted],
   'host' => 'dbserver.dev.[redacted].drush.in',
   'port' => '10677',
//   'prefix' => '',
//   'collation' => 'utf8_general_ci',
 );

```

How do I use drush on EC2 to update the local filesystem while using a remote database? What am I missing?

# Answer
> 1 votes
Looks like drush didn't like the update module disabled:

> Command pm-updatecode needs the following modules installed/enabled to run: update.

Are you sure you are running drush from inside the default site directory (which I'm assuming is your actual site directory)?

You can also set up a local site alias for your dev site so you can point to that using drush and not have to run drush from the site directory. For example, 'drush @localdev status' and 'crush @pantheon.redacted.dev status'.

---
Tags: database, drush
---


# Question
Title: Integrating a local php script into drupal block
I am trying to integrate a local PHP script (a guestbook script) into a block, but the links it outputs are not correct. They point to the index.php file used from Drupal, instead of point to its own index.php file.

Is there a way to make the links point to the right index file?

# Answer
> 0 votes
Sounds like your script is expecting to run index.php from the website root directory which is already used by Drupal. You will need to re-write the script to use a different root url or set the root url for that script.

---
Tags: blocks
---


# Question
Title: How do I update Drupal 7 to Drupal 7 DEV via Drush command line?
I have an old drupal 7 installation and I would like to update this via drush. Usually I download the drupal 7 dev version through the website using wget and untar it into the public\_html directory and overwrite everything.

I know i can update drupal modules via "drush dl " but not sure how to do it for core easily using drush.

# Answer
`drush dl` is for downloading modules the first time, not updating.

To update core to dev version:

`drush up drupal-7.x-dev`
> 1 votes

---
Tags: 7, drush
---


# Question
Title: Field collection: Can I make a field mandatory depending on another field's value?
I'm trying to set up a custom solution using Field Collection consisting of:

* term reference (autocomplete tagging style)
* plain text.

What I need to achieve is to react to Javascript event of autocomplete (but only for that field) and - if the selected term title contains a string placeholder `%1` \- make the plain text mandatory, so that user is force to enter the substitution text.

Is that technically possible or would it require setting up a custom collection from scratch?

# Answer
The Conditional Fields module can help you to achieve this.

You will probably need to create an explicit list of taxonomy terms for the case when you want the plain text field to appear and to be required instead of checking the existence of the aforementioned placeholder.
> 1 votes

---
Tags: javascript, ajax, entities
---


# Question
Title: how to remove anonymous user role from list of profile members
I want to remove anonymous role member from the public list of profile users because anonymous roles cannot join so it is confusing to see the anonymous user at top of public profile list.

# Answer
Add a filter for user: UID and set to "not equal to" and enter 0 for the value.
> 3 votes

---
Tags: views, users
---


title: Removing the breadcrumb from frontpage

text:
# Question
Title: Removing the breadcrumb from frontpage
I'd like to remove the breadcrumb from the frontpage and haven't been able to find a solution in the configuration settings of the theme or custom breadcrumbs. So I am thinking of modifying the page.tpl.php

Do you see a problem with this?

Replace:

```
<?php print $breadcrumb; ?>

```

With:

```
<?php if ($_GET["q"] == variable_get("site_frontpage",
"node")){}
else if ($breadcrumb) {print $breadcrumb;} ?>

```

# Answer
> 3 votes
You don't have to do it the hard way. There is a variable (bool) $is\_front that you can use in this case.

```
<?php if (!$is_front && $breadcrumb) {
  print $breadcrumb;
}
?>

```

You can read more about page.tpl.php variables here.

---
Tags: breadcrumbs
---


# Question
Title: How do I programmatically add and fill a field to taxonomy terms of a specific vocabulary?
I want to programmatically do two things:

1. Replace the default multiline Description field of taxonomy term with my own, plain text, single line field. I mean - to *visually* replace - I understand this is an entity property and all I can do is to hide it and create another, plain text field.
2. Populate the vocabulary through `taxonomy_term_save()` \- putting the description strings into the newly created field.

Would anyone be kind and provide a skeleton of code to achieve it?

# Answer
> 1 votes
This is really two questions.

For the first, I would use `hook_taxonomy_term_view` to alter `$build['description']['#markup']`, like so:

```
function custom_taxonomy_term_view_alter(&$build) {
  $build['description']['#markup'] .= '<p> And this is more stuff.<p>';
}

```

For the second, `taxonomy_term_save()` can take a description field as described on the API docs page.

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


title: is memcache slowing down my website?

text:
# Question
Title: is memcache slowing down my website?
Hi I have a brand new website, the upload time was around 2 seconds and after installing Memcache it s around 10 seconds, what coulds be causing this issue? website is in drupal6

# Answer
> 0 votes
I can not post an comment?

Anyway, there is not much information given about the hardware, settings etc. so from that point off its hard to say.

You might wanna retrace your steps if you are sure the uploadtime increased with 500 percent. Then you know if Memcache caused any problems, what ever the result is please update the question with more specific information.

---
Tags: caching
---


title: Adding a stock while adding a product

text:
# Question
Title: Adding a stock while adding a product
How can I add stocks in Ubercart while adding products?

I insert a new field in the product setting. How can I link the stock with the product?

# Answer
> 0 votes
Thanks for asking...monymirza. finally i find the solution .

After adding the product instead of save click save and continue it will lead to edit page whre we can add stock numbers..

---
Tags: ubercart
---


# Question
Title: Import contacts from different social networking sites and invite to my drupal site
I am in the process of building a social networking site.I need to allow my users to be able to invite their friends as well on to the site. Using the Invite module alone will not cater to my need. What i need is this to work with some other module. I want users to be able to import their contacts from Facebook, Twitter, Gmail and then select between the contacts the users to invite. I thought of using the Contact Importer module but it has issues with social networking platforms. Please advice. You may have a look at the following image to understand my use case. https://i.stack.imgur.com/RQCmA.jpg

# Answer
You would use the invite along with the Contact Importer

**Invite**

> Invitations are important to create network effects and exponential growth of a community of interest. This module provides an Invite a friend feature to allow your users to send and track invitations to join your site.

**Contact Importer**

> Contact Importer provides a form for your users to enter their email address and password. The contacts from their address book are then retrieved.
>
> Contact Importer can be used with any Drupal form. No codding necessary. It can be used with an invite module, a user import module, an emailing module, or anything else that you can think of.
>
> The current release interfaces with the Octazen or Open Inviter retrieval services. But the architecture is modular and can be very easily extended to use other retrieval services such as Contact Mines, ImproSys, or IpInvite.
> 1 votes

---
Tags: users, emails, social-network
---


# Question
Title: How to send form submitted data to paypal in Drupal?
I have setup a form where user fill some fields and choose a user type & on submission I have to send him to paypal with the values which he filled up, so that on IPN callback I receive the data from them and do something(this is the procedure I have come to know from reading paypal integration with php), I am stuck at form point because at submission I have another function where I can get the selected value by form\_state..

Here is the code --

```
<?php

//Hook_Menu for paypal callback function.
function user_type_registration_menu(){
  $items = array();
          $items['paypal/payment/ipn'] = array(
          'title' => t('Paypal Payment IPN'),
          'description' => t('Paypal Payment IPN'),
          'type' => MENU_CALLBACK,
        'file'  => 'paypal_payment.inc',
          'page callback' => 'paypal_payment_paypal_ipn_callback',
          'access callback' => TRUE,
        );
      return $items;
}

//Form alter for registration form.
function user_type_register_form_alter(&$form, &$form_state, $form_id){
  switch($form_id) {
      case 'user_register_form': // the value we stole from the rendered form
        $form['account']['user_type'] = array(
          '#type' => 'select',
          '#title' => t('Membership Type:'),
          '#options' => array(
            0 => t('General $50.00/Yr'),
            1 => t('Student $40.00/Yr'),
            2 => t('Government $60.00/Yr'),
            ),
           '#weight' => -11,
           '#description' => t('Select the membership type, which you want to have.'),
          );
        $form['account']['user_type_submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
          '#submit' => array('user_type_register_form_submit'),
          '#validate' => array('user_type_register_form_alter_validate'),
        );
        $form['account']['name']['#description'] = t('');
        $form['account']['mail']['#description'] = t('');
        unset ($form['actions']);// unset the default submit Button
        return $form;
      break;
    }
}

function user_type_register_form_submit($form, &$form_state){
  $username = $form_state['values']['name'];
  $user_email = $form_state['values']['mail'];
  $user_type = $form_state['values']['user_type'];
  $password = user_password(8);
  switch($user_type){

    case '0':
      dpm("General");
      $membership_price = 50;
      $fields = array(
        'name' => $username,
        'mail' => $user_email,
        'pass' => $password,
        'status' => 1,
        'init' => $user_email,
        'roles' => array(
          DRUPAL_AUTHENTICATED_RID => 'authenticated user',),
      );
      $account = user_save('', $fields);
      $account->password = $fields['password'];
      //--Here I have to send if to PAYPAL

      dpm("user registered");
      break;

    case '1':
      dpm("Student");
      $membership_price = 40;
      $fields = array(
        'name' => $username,
        'mail' => $user_email,
        'pass' => $password,
        'status' => 1,
        'init' => $user_email,
        'roles' => array(
          DRUPAL_AUTHENTICATED_RID => 'authenticated user',),
      );
      $account = user_save('', $fields);
      $account->password = $fields['password'];
      //--Here I have to send if to PAYPAL
      break;

    case '2':
      dpm("Government");
      $membership_price = 60;
      $fields = array(
        'name' => $username,
        'mail' => $user_email,
        'pass' => $password,
        'status' => 1,
        'init' => $user_email,
        'roles' => array(
          DRUPAL_AUTHENTICATED_RID => 'authenticated user',),
      );
      $account = user_save('', $fields);
      $account->password = $fields['password'];
      //--Here I have to send if to PAYPAL
      break;
  }
}

function user_type_register_form_alter_validate(){

}

```

I hope somebody can help...

# Answer
> 3 votes
I'm the maintainer of Drupal Commerce and of the Commerce PayPal module. I'm afraid your question is too broad to be answerable here, but for folks looking to solve the same issue, you should check out the code in my Commerce PayPal module. It provides a full integration of WPS, WPP, EC, and PPA / Payflow Link.

For general Drupal support, there are much better channels to pursue. I'd look into videos or books specifically focusing on the Forms API or just dive into module code like mine to learn through investigating working examples.

# Answer
> 0 votes
I believe Ryan is right, since your question is a bit too generic.
Still, I believe the way to try and handle those kind of tasks should be via the integration between Drupal, Commerce and Rules.

In a use case I had, I wanted to achieve some kind of user subscription for a node. To make this happen, I wrote some basic building blocks I believe you can re-use in your situation.

Full details is here, and the specific module to handle IPN via Rules is here. Hope this helps, and I will be happy to help more if needed.
Regards,
Shushu

# Answer
> 0 votes
I don't believe that you need to introduce yourself here at drupal.stackexchange, who doesn't know who Ryan is if a person is working with Drupal ?

I have very simple need. On the user registration page there is a select box for 3-4 membership type. User will fill the form, select a membership type and click submit to pay by paypal. Will be forwarded to paypal...and on payment he will return back on site. He will see him registered.

At first when this requirement came, I thought it could be easy to achieve with drupal commerce as I have used your module. But I couldn't find any way to do this simple thing. I don't have shame to say that...I am not any good at rules module(specially PHP logics to write for something). I ruined two days searching some option...trying this & that. Though I found one promising paid module name MEMBERSHIP SUITE to achieve the same, but it charge on yearly basis. Then again I went through the requirement & thought...why can't I do it by own module...I will have to alter the form, change action & send him to paypal to pay..When he returns back, I will register him in callback function.

This thing is done for now...for which I asked earlier & you have answered.

Now I am struggling with the IPN callback as it's not returning me any values which I have sent & always returning INVALID(I am working with sandbox though).

I haven't done this before & so that struggling...but I believe, this is how I will learn...

At last -- I AM BIG FAN OF YOURS & it was nice seeing you replying my post..

Thanks

---
Tags: payment-gateways
---


title: Normal View with multi language website

text:
# Question
Title: Normal View with multi language website
I have a normal view on multi language site and add a field Called website the field is displayed on en language but does not show in the another language

How i can fix this problem

# Answer
> 0 votes
thanks all . my problem is come from the model is called views i18n cuase it is override the result to anther that i have translate it

---
Tags: views, 7, forms
---


# Question
Title: what actions to take when someone uploaded php files in random drupal folders and sending out spam
I'm not sure how this happened, but my server techs notified me about some php files inside the includes folder sending out 50k worth of emails. I'm not sure how anyone would be able to upload that. I doubt its because my username/password was compromised for the domain. im finding these files littered through out the directories: http://prntscr.com/rhf93

In those files they contain all similar encoded php code:

http://prntscr.com/rgzmo

http://prntscr.com/rhfmq

Does anyone know what its doing or how i can decipher the code? And most of all how was it uploaded?

# Answer
> 0 votes
Notice how most of these code snippets begin with "preg\_replace('/(.\*)/e'"? That's because it's an alternative to the eval() function for executing PHP. The rest of the string is hexadecimally encoded; you can decode it using this script. That string will decode to PHP that probably executes other scripts or performs other actions to hijack your site and make it part of a spam mailing net.

Check out this StackExchange post for more details and suggestions. There are a bunch of good articles out there too that can give you tips on securing your server.

---
Tags: 7, security
---


# Question
Title: how to assign different default images to different roles
I have only two profiles, public and registration but I have different roles and would like to add an appropriate default image for each role.

Must I create a separate profile for each role to implement this?

# Answer
If you want to display an image for a particular user role , say "Role1" , then in page.tpl

```
 <?php global $user;
  if($user->roles[2] == 'Role1')
 {
 print $logo;
 }?>

```

Just print the $user to get in what values your role is in the role array.

If you print $user, your role may be in this,

```
 [roles](
 [1] = role1
 [2] = role2
 [3] = role3
       )

```

So choose your role and check the condition and accordingly print the $logo however before that get the image in $logo using the image source tag.
> 0 votes

---
Tags: users
---


# Question
Title: How to perform automated testing of an entire site after core changes?
I'm looking for a module which will test an entire site with each OS update, or Drupal core update. E.g. go through each node and let me know there are any 404 returned for JS or CSS files, broken links, any white screens of death, etc. And if possible if the response time of the site has drastically decreased.

I've done some search and can I only see references to SimpleTest used or unit testing. I'm looking at using Selenium at the moment.

How are other people testing sites after a core changes?

# Answer
http://drupal.org/project/simpletest \- it provides essentially the same testing API as the core D7 module and you still have to write the tests yourself. There is also http://drupal.org/project/simpletest\_automator that apparently will help you 'record' your actions on a site into a SimpleTest for you.

Additional helpful links:
> 0 votes

---
Tags: updating, testing
---


# Question
Title: Allow user to completely delete account (and data), not just cancel it
I want users to provide option to cancel their own account. I know this is supported in D7, and I am using that only. But I want it in a manner that, when a user selects to cancel that account, all of his content and comments should be deleted. Right now, it is just blocking the user account, and keeping his all content.

If I grant user the permission "Select method for cancelling own account", then he may selects the option to retain his content upon cancellation, which I don't want.

So is there any way that when user cancels his account, cancellation method will delete the user account completely, without asking user to select from options.

-- Thanks for your time.

# Answer
> 1 votes
I found it myself. It is under: `Configuration-> Account Settings-> When cancelling a user account` section.

---
Tags: 7, users
---


# Question
Title: Display hash anchor tags into drupal 7 menu items without modifying hooks or adding modules?
currently when path url in menu items are set to: `node/1#anchor` the anchor is removed.

How would you solve this?

# Answer
> 0 votes
Drupal cannot do this out of the box. However, you can use the Special menu items module to create a new menu item, and place "nolink" in the path settings.

---
Tags: 7, routes
---


# Question
Title: Content block doesn't show when query is added to the URL
I have a Drupal 7 page where some of my content blocks don't show up, if there is a query added to the URL.

Say my block is main\_content, and it is shown all all pages except the listed ones, where no page is listed; the block appears correctly on on www.mydomain.com, but not on www.mydomain.com?gclid=xxx.

This is an issue for me because Google AdWords banners are linking to my page with a query attribute, and then the page does not display correctly.

What could be the issue here?

# Answer
> 0 votes
I managed to fix this issue. I'm very new to Drupal and I'm administrating a site that someone else built. The problem was in template.php in a function called 'views\_views\_pre\_execute'. Some code was checking for drupal path alias and some custom queries was built. I changed: '$path = substr(drupal\_get\_path\_alias(request\_uri()),1);' into 'drupal\_get\_path\_alias($\_GET\['q'\]);' and now it works.

---
Tags: 7, blocks
---


title: Create webform field on node create

text:
# Question
Title: Create webform field on node create
Ok, I'm building a custom module that has content type that is webform enabled. When creating a node of this type, I need to automatically create one webform select field when node gets saved. How can I achieve this? The goal is that all webforms have this field when they're created, rest are user created.

# Answer
> 2 votes
I am not sure about your use case.

But the following module does exactly that.

Webform Default Fields

> With this module you can easily create much of nodes with same webform fields. It can be applicable in case of job vacancies with reply form, kind of quality feedback control or whatever your mind suggests you.
>
> Because you can create more than one webform-enabled content types, you respectively can attach different default fields for each of them.

# Answer
> 1 votes
```
/**
  * Implements hook_node_insert().
  */
function wf_queue_node_insert($node) {
  // Here we will force signup action field (and possibly other fields) that is default for all forms when they're created. When user adds component to the webform, select element for action to take is generated.
  if($node->type == "event") {
    // Include webform component functions. If we don't do this, we can't use webform functions needed to create element.
    module_load_include('inc', 'webform', 'includes/webform.components');

    // Check if field exists by doing database query and checking for cid = 99 on this node. TODO: This check is maybe too failsafe.
    $dbresultwf = db_query("SELECT * FROM {webform_component} WHERE nid = :nid AND cid = :cid", array(":nid" => $node->nid, ":cid" => 99))->fetchField();

    // It doesn't exists, create it.
    if(!$dbresultwf) {
      $component = array(
        // We set cid to 99 so it wont interfere with other components (This might need to be increased further for very complex forms. Does webform check for existing cid? If so we are fine.
        'cid' => 99,
        'pid' => 0,
        'nid' => (int)$node->nid,
        // Set machine name and display name
        'form_key' => 'event_action',
        'name' => t('Select an action'),
        // Type we need is a select options
        'type' => 'select',
        'extra' => array(
          'description' => 'Select an action to perform',
          'items' => 'signup|Signup' . "\n" . 'queue|Queue' . "\n" . 'cancel|Cancel',
        ),
        // This needs to be mandatory as it will be used for other functionality.
        'mandatory' => 1,
        'weight' => -99,
        'page_num' => 1,
        );
      // Insert component to webform
      webform_component_insert($component);
    }
  }
}

```

---
Tags: 7, hooks, webforms
---


# Question
Title: how to export custom installed module(s) configurations?
> **Possible Duplicate:**
> Deployment for staging and production

how can i export the change in configuration of a custom install module, configuration module is exporting configurations of these, components Content type,Field,Image style,Variable,Permission, Vocabulary.

# Answer
These are my finding. Drush provides the sync, using mysql dump and restore as complete, not the changes made after some interval. Many things can be tracked with

* Configuration Module
* Features
* Extra Features

Please see the presentation for futher. https://docs.google.com/file/d/0B6Sp-HBmxgGMMnhhQXVrR1hDUVU/edit?usp=sharing
> 0 votes

---
Tags: 7
---


# Question
Title: Showing Warning for viewing adult classified content
I am developing one publishing website, where authenticated users can write the article. For each article, he sets the age group for which the article is targeted for. Different age group may be "Adult","Pre-teens" and "Everyone". I have used `taxonomy` to age group.

Now, I want to show warning message to the user, when he goes to any "Adult", classified article page, before loading the content, and get the confirmation from the user that he is 18+ to view this article.

Please suggest how, can I implement this or is there any module that helps me to achieve this.

Thanks for your time.

# Answer
Do you want to implement the age verification for Anonymous users or for logged in users? If you are doing it only for the logged in users maybe a better option would be to just add a birthday field to the user and just verify the age on that, so you won't have to request the age all the time, or only the first time, and then store it in the birthday field.

If not, for the actual confirmation page, you could just use \*hook\_node\_view\* and if the user has not confirmed his age for that node, replace the content with the verification form. For the way you can store whether someone has confirmed his age for a node depends, as I've said above, on how you want things to work, for authenticated users, for anonymous users.
> 1 votes

# Answer
Theirs so many ways you could implement this, I personally would make a module that uses SESSIONS to remember the users age (saves them being annoyed with confirmations every time they visit the site).

Then in the module create a function that you can call on pages that you want to restrict access to.

Something like

```
function mymodule_age_verification()
{
  $age = isset($_SESSION['age']) ? $_SESSION['age'] : null;
  if ($age == null)
  {
     // print dialog asking for users age
  }
  else if ($age < 18)
  {
    //print error
    exit();
    // dont show this page they aren't old enoguh etc
  }
  else
  {
    // do nothing they are allowed to go here
  }
}

```

To prevent the node being displayed based on age you can use something like

```
function mymodule_node_view()
{
  mymodule_age_verification();
}

```

Syntax isn't exact. I will provide a more detailed syntax accurate answer if absolutely necessary.

Of course that example is very rough and basic, it would be nice to use AJAX for the age verification entry. But that should be enough to get you started.
> 0 votes

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


# Question
Title: Using computed field to calculate total hours for a datetime field but to exclude all weekend hours
Please please if can anyone help I would really appreciate it!

I have managed to get total hours between value 1 and value 2 of my datetime field however I really want to exclude any hours which are in the weekend. I am creating a timesheet for a group of carers and some people will work from a friday night to a saturday morning etc.

this is my code I use atm for calculating the total hours:

```
$start_value = $entity->field_work_hour_date[LANGUAGE_NONE][0]['value'];
$end_value = $entity->field_work_hour_date[LANGUAGE_NONE][0]['value2'];
$timezone = $entity->field_work_hour_date[LANGUAGE_NONE][0]['timezone'];

$start_date = new DateObject($start_value, $timezone);
$end_date = new DateObject($end_value, $timezone);

$duration = $start_date->difference($end_date, 'hours');
$entity_field[0]['value'] = $duration;

```

I am still quite new to drupal and php so I would really appreciate any help.

Cheers

# Answer
> 0 votes
I would :

```
$duration = $start_date->difference($end_date, 'hours');
// Place this :
if($start_date->format('Y-W') != $end_date->format('Y-W')) {
  $difweeks = $start_date->difference($end_date, 'weeks');
  $duration = $duration - intval(48 * $difweeks);
}
$entity_field[0]['value'] = $duration;

```

---
Tags: datetime
---


# Question
Title: Found index.php in files folder and all its subfolders? Anyone know what type of exploit is this?
I'm cleaning up my drupal installations and i found in the files folder there was an index.php file and all its subfolders. screenshot:

I still dont know what kind of exploit was done to get all these files in here. Anyone had something similar or know what this is?

# Answer
Just an additional note, this looks like it could have been caused by the FCKEditor / CKEditor arbitrary file upload bug.

If using one of those WYSIWYGs, check this advisory:

http://drupal.org/node/1482528

and upgrade to latest
> 3 votes

# Answer
That looks like a very dangerous exploit - they're basically able to arbitrarily pass commands through the request string ($cvjuec) and have them executed, or even write out files from the ($oktv) request string. I would suspect given the date of the attack, that the damage is already done or it was unsuccessful and they moved on. I looked for examples of this script but it may be using randomized variable names to avoid automatic detection.

Few suggestions (assuming this is a Linux system?)

* Run a rootkit scanner on your system, ex: http://www.rootkit.nl/projects/rootkit\_hunter.html and follow instructions.
* Enable php open\_basedir restrictions for this site (and others on this box?) to prevent your compromised php process from being able to write below the document root and compromising server-level files
* Check the logs for this site and see if you have a record of these attack vectors. I.e. look for urls that reference */sites/default/files/styles/index.php?cvjuec=*, or some of the other strings referenced in the above script to see if there is a record of what kinds of files they tried to install.
* Secure the permissions on your drupal folders following the instructions in the documentation to prevent unauthorized users from writing to the folder with executable permissions
* Is this a multi-site server? Are there other sites on the server that could have been compromised and allow the user to write to these folders? I've had multi-site servers before where an exploit in on non-drupal site allowed attacks on unsecure drupal sites.
* Obviously should take a look at your modules and run any necessary Drupal security updates. Security review module can give you some tips for securing Drupal sites.

Unfortunately, you're probably in clean-up / recovery mode at this point, just trying to stop the bleeding. Best case scenario is that the attacker wasn't able to install anything sophisticated enough to damage the rest of the box (perhaps because open\_basedir restrictions or PHP safe mode was already in place) and this is as far as they got. If you do detect rootkits and other tools, they may have more control of your box than you can tell and moving to a new environment may be the best option.
> 1 votes

---
Tags: security
---


title: Unlock a file download via callback

text:
# Question
Title: Unlock a file download via callback
pls I want to control a file access to download, a user will download the file only if a test condition is true. .... there is going to be an execution of a callback url from an external site, and my site will receive a signal then will unlock the file, so I use my site IP address as a test condition... if Server\_remote address of my site is = the $external callback IP address, then....unlock the file, how do I proceed on that?

if you have a better idea of implementing this, let me know too.

cheers,

# Answer
Sounds like a case for

1. Private file mode on a file field
2. A custom hook\_file\_download
> 1 votes

---
Tags: routes
---


title: Javascript Error on User sign up page

text:
# Question
Title: Javascript Error on User sign up page
I have suddenly started getting these errors on my sign up page:

1. Failed to load resource: the server responded with a status of 406 (Not Acceptable) .co.uk/misc/jquery.cookie.js?v=1.0
2. Uncaught TypeError: Object function (j,s){return new b.fn.init(j,s)} has no method 'cookie' form.js:69

Any ideas what might be causing this...

# Answer
problem was rules for mod\_security on the server being triggered.
> 1 votes

# Answer
This is due to using Autocomplete functions. Disable autocomplete module and Sure error will be gone.
> 1 votes

---
Tags: javascript
---


# Question
Title: What file permissions and ownerships are appropriate for the files directory and subdirectories?
> **Possible Duplicate:**
> What are the recommended directory permissions?

I've scoured the net, and it seems that everyone has different methods of doing this and I just want to get a quick straight answer if possible. So i'm on Centos with apache installed.

I know the files folder has to be 777, but 777 is insecure as anyone can write to it, but isn't that what we need since anonymous users have to write to it when they upload to the server like images or what not? And not to forget drupal throws an error if its not 777.

Also if my user for that domain is foo, then the ownership of files and all its items inside would be foo:foo correct? But im reading it should be foo:www-data ? so which one is it?

# Answer
It depends somewhat on your server configuration but it doesn't have to be 777, and in fact it should not be 777 as that is a security issue.

The web server user (on your server, not your drupal site) is what has to be able to write to the files directory. Whether the drupal user is logged in or anonymous is unrelated.

For information on this see http://drupal.org/node/244924
> 1 votes

---
Tags: users, security, files
---


# Question
Title: Proper way of removing/hiding unwanted elements?
There are many times where in drupal I'm styling a theme and if I don't need some element I cannot remove in settings I just hide it with css(display:none, or similar). Is it considered a bad practice to do this and should I always use hooks or some over methods?

# Answer
> 2 votes
It depends what you are hiding.

If it is something like a page or block title or labels or other semantic type markup, you should hide it using the element-invisible class, which effectively hides it but without using display: none. This way screen readers can still see the text, which helps give visually impaired users context for the subsequent content, which is required for accessibility reasons.

If you are hiding actual content, like fields, or whole blocks, or menus etc. you should not be doing it in the CSS. It is best to do it on the back end.

The time when this is most important is hiding for access control. Never use css to hide data or fields that a users should not be allowed to see. Because that data is still available to the user, it just isn't visible by default. So that would be a security issue.

For forms you can use hook\_form\_alter(), hook\_form\_BASE\_FORM\_ID\_alter() or hook\_form\_FORM\_ID\_alter().

For other areas, there are many possibilities depending on what you are themeing and what you are intending to do. Some examples, are hook\_node\_view\_alter() for node pages, hook\_user\_view\_alter() for user pages, other alter hooks, template preprocessors, theme functions and template file overrides.

For more information on drupal hooks see http://api.drupal.org For more information on overriding theme functions and template files see http://drupal.org/theme-guide/6-7

# Answer
> 0 votes
The best way is to use hook\_form\_alter to get the form and unset the form elements.

Another approach is to make the element type to hidden. i prefer the first one.

---
Tags: theming, hooks
---


# Question
Title: ERROR: duplicate key value violates unique constraint "drupal_cache_block_pkey"
Using Drupal 7.19 and standard Bartik theme at my site (in Russian language, UTF8 encoding) with PostgreSQL 8.4.13 and pgbouncer on CentOS 6.3 / 64 bit Linux I keep getting these kind of error messages in the database log files at `/var/lib/pgsql/data/pg_log/postgresql-*.log`:

```
ERROR:  duplicate key value violates unique constraint "drupal_cache_block_pkey"
STATEMENT:  INSERT INTO drupal_cache_block (cid, serialized, created, expire, data) VALUES ('user:new:bartik:ru:r.1', '1', '1359635697', '-1', 'a:2:{s:7:"subject";s:35:"\\320\\235\\320\\276\\320\\262\\321\\213\\320\\265 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\270";s:7:"content";s:1264:"<div class="item-list"><ul><li class="first"><a href="/user/24331" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">\\320\\241\\320\\260\\320\\275\\320\\265\\320\\272141</a></li>\\012<li><a href="/user/24330" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">vetall</a></li>\\012<li><a href="/user/24329" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">Karina</a></li>\\012<li><a href="/user/24327" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">sosoia47</a></li>\\012<li><a href="/user/24326" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">DD</a></li>\\012<li><a href="/user/24324" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">altabay</a></li>\\012<li><a href="/user/24323" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">\\320\\235\\320\\265\\321\\200\\320\\262</a></li>\\012<li><a href="/user/24318" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">\\320\\220\\320\\271\\320\\261\\320\\276\\320\\273</a></li>\\012<li><a href="/user/24317" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">\\320\\220\\320\\273\\320\\265\\320\\272\\321\\201\\320\\265\\320\\271</a></li>\\012<li class="last"><a href="/user/24316" title="\\320\\230\\320\\275\\321\\204\\320\\276\\321\\200\\320\\274\\320\\260\\321\\206\\320\\270\\321\\217 \\320\\276 \\320\\277\\320\\276\\320\\273\\321\\214\\320\\267\\320\\276\\320\\262\\320\\260\\321\\202\\320\\265\\320\\273\\320\\265." class="username">dejwitxyzsdaweq</a></li>\\012</ul></div>";}')

```

Clearing cache by clicking the button at the `/admin/config/development/performance` doesn't help.

Is there maybe a way to fix that by clearing one of these SQL tables?

```
 public | drupal_cache                          | table | drupal
 public | drupal_cache_block                    | table | drupal
 public | drupal_cache_bootstrap                | table | drupal
 public | drupal_cache_field                    | table | drupal
 public | drupal_cache_filter                   | table | drupal
 public | drupal_cache_form                     | table | drupal
 public | drupal_cache_image                    | table | drupal
 public | drupal_cache_menu                     | table | drupal
 public | drupal_cache_page                     | table | drupal
 public | drupal_cache_path                     | table | drupal
 public | drupal_cache_update                   | table | drupal

```

Does it make sense to submit a bug against Drupal 7?

My config data - **postgresql.conf**:

```
shared_buffers = 4096MB  # I've got 32 GB of RAM to burn
work_mem = 32MB
wal_buffers = 4MB
checkpoint_segments = 32
escape_string_warning = off  # otherwise Drupal spams me with warnings

```

and **pgbouncer.ini**:

```
pool_mode = session
server_reset_query = DISCARD ALL;
server_check_delay = 10
max_client_conn = 600
default_pool_size = 50

```

**UPDATE:** Submitted bug #1907230 against Drupal core

# Answer
This happens when we export/import. I have met this many times what i done to overcome this is to empty the cache tables and retry import.

This will work and i am glad you submitted a bug report.
> 1 votes

---
Tags: 7, caching
---


title: User Login Form Error Message Problem

text:
# Question
Title: User Login Form Error Message Problem
I'm adding the user login form to the homepage of my site and through printing it out in my page.tpl.php, the validation is getting lost a bit. The first time I enter in an incorrect username or password, nothing happens, but the second time everything acts as it should. I am confused about why it does not display the first time.

In my page.tpl.php

```
print drupal_render(drupal_get_form('user_login_block'));

```

In my template.php

```
if ($form_id == "user_login_block") {
  $form['links']['#markup'] = ' <a class="user-password" href="/user/password">' . t('Forgot username or password?') . '</a>';
  $form['name']['#title'] = t('Username'); // Change text on form
  $form['name']['#attributes'] = array('placeholder' => t('Username'));
  $form['pass']['#title'] = t('Password');
  $form['pass']['#attributes'] = array('placeholder' => t('Password'));
  $form['actions']['submit']['#value'] = t('');
}

```

My Custom Validate Module

```
function hook_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'user_login_block'){
    $form['#validate'][] = '_custom_validation';
  }
}

function _custom_validation(&$form, &$form_state){
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $query->condition('u.name', $form_state['values']['name'], '=');
  $result = $query->execute();
  $name = $result->fetchField();
  if(empty($name)){
    form_set_error('user_name', t('Username or password could not could not be found.'));
  }
}

```

I also have the module "Email Registration" Installed, not sure if this has anything to do with it also.

Would anyone know anything about this?

# Answer
What is the reason for you adding the form in that manner and having custom validation etc. when drupal already gives you this?

For example, why not just use the drupal block system or the context module to place the login block on your homepage within one of the regions?

Another thing is that your custom module should not have

```
function hook_form_alter(&$form, &$form_state, $form_id)

```

it should be

```
function MODULE_NAME_form_alter(&$form, &$form_state, $form_id)

```

Where you replace MODULE\_NAME with your module's name.
Although maybe you only had it that way for this post.

Also, regardless of the method you use to show the user\_login\_block form, it already has its own validation functions that come with it. It already has these three validation functions:
http://api.drupal.org/api/drupal/modules!user!user.module/function/user\_login\_name\_validate/7
http://api.drupal.org/api/drupal/modules!user!user.module/function/user\_login\_authenticate\_validate/7
http://api.drupal.org/api/drupal/modules!user!user.module/function/user\_login\_final\_validate/7

With the last of those doing (among other things) essentially the same validation your custom function is trying to do.

You can still use the form alter to add your attributes and change titles, etc. In this case though the module weight does not matter. It only matters if two modules are both using hook\_form\_alter() and are changing the same parts of the form.
> 1 votes

# Answer
I'm assuming the code in template.php is supposed to alter the user\_login\_block form. If so, why not move that code inside your hook\_form\_alter() function? You may also need to give your custom module a higher weight using hook\_install inside yourmodule.install:

```
/**
 * Implementation of hook_install().
 */
function mymodule_install() {
  // Module weight defaults to zero
  db_query("UPDATE {system} SET weight = 2 WHERE name = 'mymodule'");
}

```

Or if you're comfortable, edit the dB directly by incrementing the weight by one until you find the proper weight.
> 0 votes

---
Tags: forms, users
---


# Question
Title: Generate js variable before javascript loaded
I have a block with invocation code inside(it invokes js code from OpenX ads server), my site is responsive and this block get cloned(with `jquery .clone()` function) on ipad or iphone version of the site. So to avoid calling the invocation js code 2 times i need to set js variable (like this - \> `window.isScriptLoaded = FALSE`) and then inside my block i can easy do next thing:

```
if (window.isScriptLoaded == FALSE) {
    window.isScriptLoaded = TRUE;
    //invocation code...
}

```

in this case all working fine, i can easy add this variable to any js file in drupal.

But in my case `admin` can add new block and insert new invocation code - SO I need to generate `window.isScriptLoaded2` and **output this variable BEFORE code in block is loaded**

i tried next thing

```
function HOOK_page_alter(&$page) {
  //get all the variables
  //i generate my variables in database
  $var = db_query("SELECT * FROM {banners}")->fetchAll();
     $full_array = array();
     foreach($var as $object) {
         //for example Anyvariable = FALSE;
         $array[$object->name] = $object->value;
     }
      drupal_add_js(array('common' => array(
    'vars' => $array,
    )), 'setting');

}

```

this works but, code in block is loaded before `drupal.settings.vars.Anyvariable` is loaded. So my variables is always false

# Answer
It is also hard to say if this will work without seeing exactly what you need to do, but you may want to play with the scope, group, and weight options for `drupal_add_js()`. These may help you get the order that you need. From the docs

> The exact ordering of JavaScript is as follows:
>
> * First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme.
> * Then by group.
> * Then by the 'every\_page' flag, with TRUE coming before FALSE.
> * Then by weight.
> * Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal\_add\_js() that happened later in the page request gets added to the page after one for which drupal\_add\_js() happened earlier in the page request.

When I have been in similar situations, I implement a `template_preprocess_html()`, create some markup, stuff it into `$variables`, and then output this before the `print $scripts` in html.tpl.php I have to use this in some very specific situations where I need to output JS very early in the `<head>` before CSS and JS is loaded.
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to disable PHP files from being run in the sites/default/files directory?
By default does drupal 7's sites/default/files directory disables running of PHP files?

# Answer
> 0 votes
No - by default you have to create this directory so its up to you to make sure that the proper permissions are set to make sure its not world-writable and the executable bit is removed. Specifically, check the documentation on permissions -- you want to create this folder and set your permissions to allow the web-server user to write to the folder but not allow files to be uploaded that can be executed from here.

```
[root@localhost]cd /path_to_drupal_installation/sites
[root@localhost]find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
[root@localhost]for d in ./*/files
do
   find $d -type d -exec chmod ug=rwx,o= '{}' \;
   find $d -type f -exec chmod ug=rw,o= '{}' \;
done

```

Worst case scenario I've seen is a world-writable files folder that allows a malicious user to upload a PHP rootkit that can be executed and compromise the server.

# Answer
> 7 votes
By default, when you site is created a .htaccess files is put in your sites/default/files directory (or wherever your public files are) and your private directory (if defined). See `file_ensure_htaccess()` and `file_create_htaccess()` for the details.

The first line of each should read

```
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

```

This is an Apache directive that resets how it handles the files in that directory, and all subdirectories. Basically, it resets the handler to a non-existent function, which prevents files from being executed. See SA-2006-006 - Drupal Core - Execution of arbitrary files in certain Apache configurations security advisory for more info. I have double checked this on a few of my servers, and this does prevent PHP from being executed.

If this line is missing, then you need to figure out what happened and how it was removed.

If this not preventing execution by Apache, then you need to look at your server configuration. It is also conceivable that PHP may be executed here from the CLI via some server exploits.

---
Tags: security
---


# Question
Title: How can I save what filters a user wants when viewing a view?
I don't know if this is possible but, I would like to allow my users to be able to filter out what content they would like to show up in a view so that every time they return to that view, their preferences are saved.

I no how to allow my users to filter content in a view but I'm having trouble saving it. I'm trying to allow my users to control their own news feeds.

I've tried looking around for a module to do this and I've been playing around with views for a while but I can't seem to hack something thing that does what I outlined. Any help would be appreciated. Thanks.

# Answer
If your view is using exposed filters, there is a "Remember search" option in the View configuration. This stores the search parameters in the session, and should give you the expected effect. Admittedly, I'm thinking of Views 2, and I just assume the setting is available in Views 3 as well.
> 1 votes

# Answer
Since my initial answer doesn't persist the search between user-login/logout, here's a solution that will require significantly more work, but is permanent.

Create a module, with a two column table. One for uid, and one for serialized search parameters.

Implement hook\_views\_query\_alter().

In this hook, you can add the SQL needed to both fetch old data, and update with new. You should be aware however that such a solution can quickly become a heavy DB-burden, as you potentially add a lot of writing to the DB.
> 1 votes

# Answer
The Views Saved Searches module will save the filters used even if they log out. Here is a quote about it (from the module's project page):

> ... allows you to save your current configuration of exposed filters for later use. This can be especially useful for Views with a lot of exposed filters.
>
> Whenever a View is changed, all saved searches for that View are deleted, to prevent corruption. If the user has JavaScript enabled, the saving and deleting process happens through AHAH, and the new section is displayed below the exposed filters section. When JavaScript is disabled, the new section is displayed above the exposed filters section.
> 0 votes

---
Tags: 7, views, users
---


# Question
Title: Query pager not showing for administrator
I am having an interesting problem with paging the results of a query. The pager is visible to all users except those who are assigned the built-in 'administrator' role. I have tried the code on two separate Drupal installs and the result is the same: the administrator cannot see the pager. The markup is not visible in the page source.

I have tried my solution using both EntityFieldQuery and db\_select, but the problem persists. Here is the code for the EntityFieldQuery version:

```
function build_area_table() {
  $header = array(
    'area_name' => array(
      'data' => 'Area',
      'type' => 'property',
      'specifier' => 'title',
      'sort' => 'asc',
    ),
    'level_range' => array(
      'data' => 'Level range',
      'type' => 'field',
      'specifier' => array('field' => 'field_area_level_range', 'column' => 'value'),
      'sort' => 'desc',
    ),
  );

  $query = new EntityFieldQuery();
  $query = $query->pager(5); # I have more than 5 rows being returned
  $query = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'area')
    ->propertyCondition('status', 1)
    ->tableSort($header);

  $result = $query->execute();

  $nodes = null;
  // $result['node'] contains a list of nids where the title matches
  if (!empty($result['node'])) {
    // You could use node_load_multiple() instead of entity_load() for nodes
    $nodes = node_load_multiple(array_keys($result['node']));
  }

  // do something to output your results here.
  $td = array();
  foreach ($nodes as $area) {
    $td[] = array(
      'area_name' => array(
        'data' => l($area->title, 'node/'. $area->nid),
        'class' => array('area-name'),
        ),
        'level_range' => array(
          'data' => $area->field_area_level_range['und'][0]['safe_value'],
          'class' => array('level-range'),
        ),
    );
  }

  $areaTable = array(
    'area-table' => array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $td,
      '#empty' => 'No areas to display.',
    ),
    'area-pager' => array(
      '#markup' => theme('pager')
    ),
  );

  return $areaTable;
}

```

The table is rendered using Drupal 'render' in the template page. Does anyone have any ideas as to what the problem may be? I have read some posts regarding changing the pager ID, but any changes I make do not seem to have any effect.

EDIT: I am **not** using the Views module, which seems cause a conflict with pagers as reported by many other people.

Thanks!

# Answer
> 4 votes
Looks like I found the answer. It appears easier (and more efficient) to use the db\_select instead, at least for the number of fields I am sorting on. As suspected it was the pager colliding with another pager on the page, although I am not sure what pager this could be. The pager seems to working fine for all users now that I added '-\>element(0)' to the db\_select. Here is some code:

```
function build_area_table() {
  $header = array(
    'area_name' => array(
      'data' => 'Area',
      'field' => 'n.title',
      'sort' => 'asc',
    ),
    'level_range' => array(
      'data' => 'Level range',
      'field' => 'flr.field_area_level_range_value',
      'sort' => 'asc',
    ),
  );

  $query = db_select('node', 'n')
            ->extend('PagerDefault')->element(0) # fix displaying pager for all users
            ->extend('TableSort');
  $query->join('field_data_field_area_level_range', 'flr', 'n.nid = flr.entity_id');
  $result = $query
    ->fields('n', array('nid', 'title'))
    ->fields('flr', array('field_area_level_range_value'))
    ->condition('type', 'area')
    ->limit(2)
    ->orderByHeader($header)
    ->execute();

  # build the table
  $td = array();
  foreach ($result as $area) {
    $td[] = array(
      'area_name' => array(
        'data' => l($area->title, 'node/'. $area->nid),
        'class' => array('area-name'),
        ),
        'level_range' => array(
          'data' => format_area_level_range($area->field_area_level_range_value),
          'class' => array('level-range'),
        ),
    );
  }

  $areaTable = array(
    'area-pager' => array(
      '#markup' => theme('pager')
    ),
    'area-table' => array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $td,
      '#empty' => 'No areas to display.',
    ),
  );

  return $areaTable;
}

```

I could probably achieve the same using EFQ, although I can't find an EFQ version of '-\>element()'. I tried specifying the element via theme like so:

```
theme('pager', array('element' => 0))

```

but there would need to be some kind of check based on the user role, as 0 works for administrators but not for other roles and vice versa. Hopefully this can save someone else some time as well!

---
Tags: 7, paging
---


# Question
Title: How to change the view mode programmatically?
I want to change the view mode of node programmatically. I used `hook_preprocess_node(&$vars)` and set the view mode:

```
function moduleName_preprocess_node(&$vars) {
      // if conditions to apply particular view mode
      $vars['view_mode'] = 'teaser';
      $vars['elements']['#view_mode'] = 'teaser';
}

```

But this is not working as expected. Am I missing something here?

# Answer
> 13 votes
Altering the view mode in the preprocess function is doing it too late.
The correct way to alter the view module is implementing hook\_entity\_view\_mode\_alter(), which is called before the entity content is rendered. For example, in node\_view(), that hook is invoked from node\_build\_content(), which is the first function called from `node_view()`.

```
  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);

```

# Answer
> 6 votes
If you need to just change it for certain pages, I'd suggest View Mode Page. It's pretty handy and simple to use.

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


# Question
Title: How to select nodes of a certain type, created by a certain user and which have reference field to a node equal a certain nid?
```
function mymodule_get_nodes_by_user_referencing_nid($type, $userid, $referncenid) {
    return node_load_multiple(array(), array('type' => $type, 'uid' => $userid, ??? => ???));
}

```

I need a function that lists nodes by following this logic: give me all nodes of a given type which are created by a given user and which have a node reference field referencing a given node id.

Any ideas about such function (in PHP, not in Views) )?

# Answer
This code assumes you're using the entityreference module using field name "field\_reference":

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition('type', $type);
$query->propertyCondition('uid', $userid);
$query->fieldCondition('field_reference', 'target_id', $referenceid);
$result = $query->execute();

$nodes = array();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

```
> 5 votes

# Answer
The `EntityFieldQuery` class was made for just that:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type)
  ->properyCondition('uid', $user_id)
  ->fieldCondition('field_name_of_field', 'target_id', $nid);

$results = $query->execute();

if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
}

```

Note that `target_id` is the name of the column for an Entity Reference field; if you're using the References module it will be `nid` instead.
> 4 votes

---
Tags: nodes
---


# Question
Title: List all users whose "member for" and "last access" are the same
I have around 40,000 users on my site but around 20,000 of them are automated registrations (by comment spammers presumably) and I'd like to delete those.

It's very easy to spot them as their registration date/time is exactly the same as their last access date/time.

How do I filter the user list in Views so that I only get users whose "member for"=="Last access"?

# Answer
These won't be exact matches. It uses a `timestamp` value that will vary, even if only a few seconds.

I would suggest doing this in some custom PHP

that module, or writing your own custom functions. you'd convert the `timestamp` difference to a reasonable value (say, within 1 hour?) and then `user_delete()`

I would also add a captcha and/or email verification to help prevent this.
> 0 votes

---
Tags: views, users, advertising
---


# Question
Title: Allow users to email a file and create a new post
Tumblr allows users to upload files using a randomly generated email account that is assigned specifically to each user. I have a content type called "Video" and I would like to find a way to randomly generate an email address using my site's domain and allow the user to attach a video file and meta data. When they send it, it gets uploaded to the site just like it would if they submitted the form online. I am also using Amazon SES if that could be helpful to solving this.

# Answer
> 1 votes
You have two options. The less efficient (but easier) way is to keep it in Drupal

The more efficient (and more difficult) way is to do a bit of this outside Drupal and hack at your MTA and/or use something like Amavis to do it.

Since you're on a Drupal site, I'll give you a quick rundown of how I might do this if I had to keep it in Drupal.

What you need to do is have the random generated email checked by Drupal regularly.

Create a module that periodically (via cron) logs in to each user's associated email address (these should be IMAP accounts!). If it finds a message that has the right subject line to trigger a new content post, then download the attachment and save it to the file system.

Keep in mind, this could be a crazy thing to do if you're dealing with a lot of users. The better option would be to have the emails processed outside of Drupal, and then use something else to trigger the Drupal content creation.

No matter which way you go, you're looking at quite a bit of programming. I have never seen a module that does this.

---
Tags: nodes, emails, files
---


title: How to handle large taxonomy

text:
# Question
Title: How to handle large taxonomy
Have a page on website where exposed filter is hierarchical taxonomy (Country/City). Works fine with few terms, just for test. Page loadtime is 1.5ms, choosing terms goes in blink.

Now i imported all Europe countries and cities, around 5000 terms. Page loadtime is 21s. Choosing first term (parent/UK) took 8 seconds. Choosing 2nd term (child/London) took 8 seconds. I am using views exposed filter http://drupal.org/sandbox/ser\_house/1832320.

I am aware that this module is far from done but from what i found out reading about taxonomy is that Drupal handles large taxonomies very bad.

All countries and cities will be around 20.000-30.000 terms and i except several users using the filter at same time which is not an option with loadspeed so high.

Any help how to handle this (maybe another module?) would be greatly appriciated.

# Answer
> 1 votes
If still relevant, you can try out Taxonomy Edge.

It has optimizations for taxonomies in general, and also implements views filter/arguments for taxonomies.

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


# Question
Title: Is there a way to show the content of a field taken from the user profile in the comment.tpl.php file?
How does one display a custom field from a user's profile in comment.tpl.php?

# Answer
> 2 votes
The comment.tpl.php template file receive a `$comment` value, which contains the comment object. Between its properties, there is `$comment->uid`, which can be used to get the user object for the author of the comment, with `user_load($comment->uid)`. If you are instead interested in the author of the node containing the comment, then you can use the following code.

```
$node = node_load($comment->nid);
$uid = $node->uid;
if ($uid) {
  $user = user_load($uid);
}

```

In both the cases, the code should be used in the preprocess function, not in the template file used for the comments. In this case, `$variables['comment']->uid`, and `$variables['comment']->nid` are instead used.

---
Tags: entities, users, comments
---


title: Programmatically save altered file

text:
# Question
Title: Programmatically save altered file
As I mentioned in my previous question I'm attempting to write tests for a patch that will, ideally, trigger the creation of a redirect if the URI of a file changes.

My patch uses hook\_file\_update() which is called whenever file\_save() runs.

Currently this chunk of code:

```
  // Move file to new URI
  $new_uri = 'public://qwerty.png';
  file_save($test_file);
  $test_file->uri = $new_uri;
  file_save($test_file);

```

This calls my hook and creates the redirect, but the redirect fails because `drupalGet($new_url)` returns a 404.

`file_save()` returns the error, `filesize() [function.filesize]: stat failed for public://qwerty.png`.

I've tried `file_save()` on URIs that linked to existing files, which gives an error, I've tried it on not-yet-extant URIs (as above), which gives an error, and I've tried `file_move()`, which doesn't call `hook_file_update()`.

How can I programmatically change the URI of a file and trigger `hook_file_update()` inside a test?

# Answer
The way I ended up getting around this was:

1. Upload my file as an unmanaged file at the new URI
2. `$test_file->uri = $new_uri;`
3. `file_save($test_file);`
4. `file_unmanaged_delete($old_uri);`

It didn't like it when I used a URI that was not yet in existence, nor one that was already in use by a managed file, but using one that goes to an unmanaged file seemed to work fine.
> 0 votes

---
Tags: testing, files
---


# Question
Title: Can you display a variable in a Drupal webform component label?
I'm trying to create a webform in Drupal 6 where the label of a select webform component is rendered using the contents of a variable. For example:

client\_name = "Starbucks"

and I would like the label of 5 or 5 different webform components to include "Starbucks". I prefer to code this with a variable, as this webform will be cloned in the future.

Is there a way to do this? From what I can tell, labels do not accept Drupal tokens and I'm not sure where to define the variable.

any help is appreciated!

# Answer
You can alter form elements, including labels with `hook_form_alter()`. Use `dpm()` (from the Devel module) to inspect the `$form` array to find the value you want to change.
> 0 votes

---
Tags: webforms
---


# Question
Title: Creating a system account used by a module: Is setting the password with drupal_random_bytes() too excessive, or is there a better method?
I am planning to create a module that would use a system account similar to the Community user seen on Stack Exchange sites. As the system account would have permissions that normal users don't have, I would like to avoid somebody logs in with that account, and get permissions that a site maintainer would have.

Is using drupal\_random\_bytes() to create a password a good method, or is it too excessive, and I should use a different method? In any case, I was thinking of periodically changing the password; I guess this means I could use a faster way to generate the password, as long as the password is still random, and with at least X characters.

# Answer
Another option is to use `user_password()` to get the password string. When Drupal hashes it, for example during `user_save()`, with `user_hash_password()`, `drupal_random_bytes()` is used as part of the `_password_generate_salt()` calculation.

You may also be interested in preventing login through the UI by that account with validation handler added to the login form.
> 4 votes

---
Tags: users
---


title: How to disallow spam in tag field

text:
# Question
Title: How to disallow spam in tag field
We are a a job site where we allow visitors to post Jobs / Events through various forms. However it looks like that spammers are using this process to put spam in tag fields. This has resulted into tag cloud being spammers paradise.

How can I restrict that?

# Answer
> 0 votes
If you add something like

reCAPTCHA

to your form, that should stop the spammers in their tracks.

If the form is auto-populated by a bot, it should prevent adding spam content in any of the form fields as they won't be able to submit the form without passing the challenge.

---
Tags: taxonomy-terms
---


# Question
Title: Render entity reference field with link in node template
I have a content type with an entity reference field to select a user. Now I would like to render this field in the node template so that the field links to the user profile. I set the format of the field to "Label" in Manage Display and clicked on the gear so the label is linked to the reference entity.

But because I am printing the field programmatically it doesn't seem to work.

Here's what I do in my node template:

```
$field_user = field_get_items('field_collection_item', $item, 'field_user');
$field_user_output = field_view_value('field_collection_item', $item, 'field_user', $field_user[0]);
print render($field_user_output);

```

Does anyone know how to do this?

# Answer
> 0 votes
If the field is configured to display and available on the node, in `node.tpl.php`, you should be able to use:

```
print render($content['field_user']);

```

---
Tags: 7, theming, entities
---


# Question
Title: Add description to files uploaded by the Media file selector widget
I am using D7 with media module. I have a field for (multiple) files.

Instead of the built in "file" widget for the file field, I am using the "Media file selector" widget.

In drupal core's "file" widget, I am able to select the "Enable Description field" option to label the files. I am unable to find such an option with the "media file selector"

There is a whole section to add files with many fields. But I am looking for a field with some sort of description or title option. I will use it as the link text, instead of the file name.

Is there an option somewhere that I've been missing?

Thanks.

# Answer
With the file\_entity module you can add fields to files. So in your case add a "Description" field to your image file type.

When selecting how the field will be rendered, make sure to choose "Rendered file" and it display the file with the extra fields.
> 2 votes

---
Tags: 7, entities, media
---


title: Making a field sortable in Views

text:
# Question
Title: Making a field sortable in Views
What makes a field sortable in views?

I have 5 fields output in a table and only two (Node Title and an int) are sortable the rest (mixture of content taxonomy and node reference) are not sortable.

Is it possible to add in this functionality via code?

# Answer
> 2 votes
The `query_alter` function allows build a custom module with the posibility of change sort order of a view. With this function you can add directly to your sql the respective declaration to sort results.

look this guide http://www.adworkshop.com/blog/2011/05/drupal-6-tutorial-exposed-sort-views-2 that show you how to create your query\_alter and create the respective html control to your view (in this case is a dropdown menu).

this is the query\_alter function:

```
function example_exposed_sort_views_query_alter(&$view, &$query) {
if( isset( $_GET['sortoptions'] ) ) {
if ( $_GET['sortoptions'] == 'az' )
 $query->orderby[0] = 'node_title ASC';
else if ( $_GET['sortoptions'] == 'za' )
$query->orderby[0] = 'node_title DESC'; } }

```

and this is the example of html control using a dropdown menu using in this case the template `views-exposed-form.tpl.php`.

```
<?php
$sortOp = '';
if ( isset($_GET['sortoptions']) ) $sortOp = $_GET['sortoptions'] ;
?>
<label>Sort Name</label>:
<input type="radio" id="sortoptionsA" name="sortoptions" onchange="javascript:$(this.form).submit();" class="form-submit" value="az" <?php if ($sortOp == 'az') print "checked"; ?> />A-Z
<input type="radio" id="sortoptionsZ" name="sortoptions" onchange="javascript:$(this.form).submit();" class="form-submit" value="za" <?php if ($sortOp == 'za') print "checked"; ?> />Z-A

```

# Answer
> 0 votes
Did you try these modules: lineage and maybe views\_bonus ?

I searched on drupal.org regading your question and here are some findings:

According to ***Support node sort by taxonomy vocabulary for Taxonomy module*** (read here) the standard feature to sort by taxonomy vocabulary was postponed till Drupal 8 (D8).

Here you can find more related information:

This guide explains how to "***Create a view on a node reference field***" and how to set the view sort criteria for node reference fields.

# Answer
> 0 votes
As barraponto commented, it is right there in the table style settings.

---
Tags: views, 6
---


# Question
Title: Need to give a user "superadmin" status through database
There doesn't appear to be a superuser on the users table. Whenever I try to access permissions directly I get "Access denied", even though my user is listed as and Admin.

How can I promote another user to superuser status through the database?

# Answer
> How can I promote another user to superuser status through the database?

There's only one "superuser" or root user in Drupal. That user has uid 1

Perhaps you need to update that user's password.

In D6, using just SQL, you can go

```
UPDATE users SET pass = MD5('password') WHERE uid = 1;

```

and then login with that username and password.

Note, make sure that's ok with the current uid 1 user, if it's not you.
> 2 votes

# Answer
Super user is always uid 1, as mentioned in the other answer.

If you hav deleted the super user you can add a new one by either:

Create a new user, then in the database update their uid to 1.

OR

You could also run this database query to add the user manually:

```
INSERT INTO users (uid, name, pass, mail, theme, signature, status, language, picture, init, timezone_name)
values (1, 'your username', MD5('password'), 'your.email@example.com', '', '', 1, '', '', 'your.email@example.com', '');

```

When manually creating a user like that you should then go into their user account page and set check all the settings are what they should be.

Also, if someone has accidentally deleted the user 1 user that is bad. If you have other administrators that have the administer users permission, you should use the userprotect module and configure it so that those users cannot mess with user 0 or user 1.
> 0 votes

---
Tags: 6
---


title: ubercart - many "in checkout" orders

text:
# Question
Title: ubercart - many "in checkout" orders
I have a problem that too many of the orders coming in don't get completed and remain in checkout. It appears as though it doesn't even try to send to paypal.

I don't think that the issue is that the form is failing validation because of 2 reasons:

1. wouldn't most of these people try to correct their info and submit again?
2. i have also javascript validation on the page.

This issue has been with me for quite some time, and I would LOVE to get rid of it...

# Answer
> 1 votes
In checkout is a stage when someone adds something to the cart but does not go through the checkout process. It has nothing to do with the way your site functions. Just the user didn't want to checkout.

This problem (most likely) is Shopping Cart Abandonment (Google it).

UC Followup is a module that helps users push through "Adondoned Carts". http://www.drupalmodules.com/module/ubercart-followup

# Answer
> 0 votes
If you do not mind to alter the core code there is a solution http://www.ubercart.org/forum/support/6399/many\_incomplete\_orders\_in\_checkout\_status\_what\_could\_it\_be

---
Tags: 6, ubercart
---


# Question
Title: How to configure the YouTube Field and Mediafront modules?
I was told that the latest dev version of MediaFront has support for the YouTube field module. How do you configure the fields and the modules so that the embedded YouTube video is displayed using the MediaFront player?

What I'm trying to do: I have a content type that allows for YouTube URLs to be copied in it creates a list of all the YouTube videos that were entered in that node. I want MediaFront to use that list of YouTube URLs in the MediaFront player.

Also in the read it says this:

```
 7. Change the Manage Display settings for Media link.

    Set up the fields in this order and with these settings:

    Field           Label       Format
    Body            Hidden      Default
    Media URL       Hidden      MediaFront Player

    In the Media URL player settings, set the MediaFront preset to
    nodeplayer. Hit Update. Hit save.
            "

```

I cannot enable the MediaFront player for the textfield "Media URL".

# Answer
> 1 votes
Edit your textfield (admin/structure/types/manage/media/fields/\[YOUR\_TEXT\_FIELD\]). Under the Mediafront settings Field type, set field type to 'Media' and Media Type to 'Media Content'.

You must create a mediafront preset (admin/structure/mediafront) before you can associate the textfield to mediafront player.

After your preset is setup, go to manage field of your content type (admin/structure/types/manage/\[YOUR\_CONTENT\_TYPE\]/display). For the testfield that stores your media url, set the Format to Mediafrontplayer and set set the player settings to the Mediafront preset that you created.

---
Tags: media, files
---


# Question
Title: Entity Reference- How do I display more than one view mode?
I am using entity reference to display some nodes. In manage display, I am rendering my entity reference content with teaser view mode. However, I need to display the first node different. I need the first one with a picture and the other ones I just need the date, text and a link. Something like in the picture.

# Answer
I solved by using the module entity reference multiple display which let you to configure different view modes for your field reference. You can split in groups to achieve that.

You install the module and after it is enabled, you go to your content type and in manage display choose rendered entity with different view modes. I have attached a picture

From then you can choose how many groups you would like to display in my case I just need two, the first one I needed to be displayed as view mode teaser and the second one I need no picture in the teaser and just need to display at most two elements in that group.

If anyone has another way to handle this please post your answer here.
> 7 votes

---
Tags: 7, entities
---


# Question
Title: Moving site to new domain on the same server
We're having a problem (well, a series of problems actually, but this one appears more difficult to solve) moving a clients site to a new domain on the same server / hosting account.

The site is moving to another folder hosted on the same server, so should be no need to change database settings or move the database.

We've moved all the files to the new sub directory and the problem is that whilst the home page displays fine, none of the other pages appear to exist and none of the menu links work. Base URL isn't specified in the settings file (although we've tried specifying one which didn't help).

Any ideas?

EDIT: Changing .htaccess file isn't helping

# Answer
Check your `.htaccess`

Open your htaccess and modify line 94 to match your needs.

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /YOUR-FOLDER-NAME
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

```

If this not work the problem is with your cache tables or custom code in `template.php` or in `.module` files

To clear cache tables you can try

```
drush cc all

```

OR Try this in phpMyAdmin or mysql console.

```
TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_rules`;
TRUNCATE `cache_token`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;

```

Make sure you include all tables starting with **CACHE\_**

More info here Can any of the cache\_\* be emptied safely?
> 3 votes

# Answer
Is override all set in your apache config? If not this may stop your .htaccess files from being processed.

Try yoursite.com/index.php?q=uri/of/a/path/that/should/exist

instead of

yoursite.com/uri/of/a/path/that/should/exist

to test.
> 1 votes

---
Tags: 7, migrations
---


title: Titles not showing for tabs pages

text:
# Question
Title: Titles not showing for tabs pages
Below is the array in my hook\_menu

The only issue that I have with it is that the titles are not displaying for tabs pages (the last three array collections).

They are showing the title for the parent: 'Affiliate Hoover Home page'.

I've tried title callback instead but that isn't working

```
$items['admin/config/affiliate_hoover'] = array(
    'title' => 'Affiliate Hoover Home page',
    'page callback' => 'drupal_get_form',
    'description' => 'This is the affiliate hoover homepage - add shit here',
    'access arguments' => array('access content'),
    'page arguments' => array('affiliate_hoover_first_form'),
    'file' => 'affiliate_hoover.home.inc',
    'menu_name' => 'Affiliate Hoover',
    'type' => MENU_NORMAL_ITEM,
    );

$items['admin/config/affiliate_hoover/uniquename/%'] = array(
    'page callback' => 'affiliate_hoover_unique_name',
    'access arguments' => array('access content'),
    'page arguments' => array(4),
    'file' => 'affiliate_hoover.uniquename.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'title callback' => 'affiliate_hoover_uniquename_title_callback',
    'title arguments' => array(4),
    );

$items['admin/config/affiliate_hoover/uniqueform/%'] = array(
    'page callback' => 'affiliate_hoover_unique_form',
    'access arguments' => array('access content'),
    'page arguments' => array(4),
    'file' => 'affiliate_hoover.uniqueform.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'title callback' => 'affiliate_hoover_unique_form_title_callback',
    'title arguments' => array(4),
    );

$items['admin/config/affiliate_hoover/ajax'] = array(
    'type' => MENU_CALLBACK,
    'file' => 'affiliate_hoover.ajax.inc',
    'page callback' => 'affiliate_hoover_ajax_callback',
    'access arguments' => array('access content'),
    );

$items['admin/config/affiliate_hoover/'] = array(
    'title' => 'Home',
    'type' => MENU_LOCAL_TASK,
    'access callback' => TRUE,
    'weight' => -10);

$items['admin/config/affiliate_hoover/delete'] = array(
    'title' => 'Delete',
    'type' => MENU_LOCAL_TASK,
    'file' => 'affiliate_hoover.delete.inc',
    'page callback' => 'affiliate_hoover_delete_page',
    'access callback' => TRUE,
    );

$items['admin/config/affiliate_hoover/log'] = array(
    'title' => 'Log',
    'type' => MENU_LOCAL_TASK,
    'file' => 'affiliate_hoover.log.inc',
    'page callback' => 'affiliate_hoover_log_page',
    'access callback' => TRUE,
    );

$items['admin/config/affiliate_hoover/tracking'] = array(
    'title' => 'Tracking',
    'type' => MENU_LOCAL_TASK,
    'file' => 'affiliate_hoover.tracking.inc',
    'page callback' => 'affiliate_hoover_tracking_page',
    'access callback' => TRUE,
    );

return $items;

```

# Answer
If you have static titles of submenus I suggest you to return using 'title' value in array.

I guess: set static titles and 'title callback' to false.
> 0 votes

# Answer
There is drupal\_set\_title you can try this in menu callback functions.

```
drupal_set_title($title = NULL, $output = CHECK_PLAIN);

```

> **Parameters**
>
> **$title:** Optional string value to assign to the page title; or if set to NULL (default), leaves the current title unchanged.
>
> **$output:** Optional flag - normally should be left as CHECK\_PLAIN. Only set to PASS\_THROUGH if you have already removed any possibly dangerous code from $title using a function like check\_plain() or filter\_xss(). With this flag the string will be passed through unchanged.
>
> **Return value**
>
> The updated title of the current page.
> 0 votes

---
Tags: 7, routes
---