title: Advice - Forms and Credit Card Security

text:
# Question
Title: Advice - Forms and Credit Card Security
I'm working on a website for a client where he wants a order form created and e-mailed back to him. Because of the nature of the business, the card cannot be charged until the order is verified that all the items are in stock and the shipping cost verified - then they charge the card themselves. So the form is supposed to gather the card numbers. The problem is that when I use a webform, it actually SAVES the credit card number! YIKES!! I've created a PDF interactive form, which I think is a much better and safer option, but I can't get the PDF to display on the page like the customer wants.
Does anyone have any advice on what I should do or look into?? Thanks so much!!

# Answer
It's not secure at all to store or send credit card numbers in the database and via plain text email. Without careful consideration bad practice to do so.

I think you need to rethink the order fulfilment process.

You should instead consider using the refund feature of your payment gateway to refund payment after the transaction is completed, if it fails validation.

Alternatively, look at providing some sort of API process so the stock and shipping details can be verified during the checkout process, prior to payment.

There's also an option of "Authorize" vs "Capture" payment modes provided by some payment gateways to allow delayed payment capture.

In the meantime, please review PCI Compliance requirements:
> 3 votes

# Answer
In my opinion, saving plain text credit card details to your website is absolutely out of the question.

Also, emailing credit card details is out of the question.

Just don't do it ever.

It would help to know what payment gateway you are to be using because then we could give advice based on their API.

For example, in Australia I almost exclusively use eWay.

Now eWay has what they call stored payments, which is where you send them the transaction, which is stored with them securely and not processed until you send them an approval.

So in this case the checkout process would create a stored payment and then at a later date, the customer or your admin can approve it, which actually charges the credit card.

For reference you can see the eWay info pages on this:

Most reputable payment gateways should have an equivalent service.

Then it is just down to whether or not there is a drupal module already out there that integrates with the specific API you require. If not you will have to either make one that fits with your e commerce setup or make a custom module that doesn't integrate with something else (like ubercart or commerce) but just communicates with the gateway as required.
> 1 votes

# Answer
You may be able to store or email the credit card number (or PAN as its often called) if you encrypt it in some way.

The fundamental problem is a mix of what is secure and PCI compliance. It's not a matter of what's "legal or illegal" but what terms of the contract are with the merchant gateway. Storing the PAN may break those terms.

What is your plan for the store to become PCI compliant? If you don't have a plan, you'll need to get one :) The plan is likely "hire someone to do a review and then implement any advice from the review." I suggest getting in touch with whomever you plan to do the review and ask them if storing the PAN will be OK if you encrypt it. I suggest the Encrypt module if you do find out that's OK.

If the client refuses to spend money on PCI compliance then you have to ask what risk you're willing to accept as the site builder. If you do store the PAN or send it in an email you won't be the first programmer to do it. It's risky and probably not a good idea, but...if you do go ahead with it I suggest writing a physical letter to your client advising them of the risks and why they shouldn't do it and getting them to sign the letter. On a related note: do you have a general commercial insurance policy? :)
> 0 votes

---
Tags: forms, security
---


# Question
Title: How can I change a menu link dynamically? (D7)
I'm trying to change the link of a menu item dynamically based on the language that is selected in the language switcher.

Let's say I have the following links in my main-menu:
-Home
-About
-Products

If the language selected is English, I want the About item to link to node/73. If the language selected is Dutch, I want the About item to link to node/74.

Is this possible and how would I best go about this?

Any help is very much appreciated.

EDIT: Some extra information. I have the Internationalization, Content Translation and Entity Translation modules installed. Because of the hierarchy of the menu and a mix between content translated nodes and entity translated nodes, I don't want to add two seperate links to the menu but have one link and change the path dynamically in code.

# Answer
You want to implement hook\_translated\_menu\_link\_alter().

This hook is not called for all menu items. According to the API documentation:

> It is only invoked if $item\['options'\]\['alter'\] has been set to a non-empty value (e.g., TRUE). This flag should be set using hook\_menu\_link\_alter().

Here's an example:

```
function MODULE_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['options']['alter'] = TRUE;
  }
}

function MODULE_translated_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['href'] = 'node/5';
  }
}

```

Some notes:

* you may want to filter additionally by $link\['menu\_name'\]
* MODULE\_menu\_link\_alter() is invoked on cache clear for all menus items declared via hook\_menu().
* For menu items created via web **it is only invoked on save**, that is, for this code to take effect you need to edit-and-save menu links you want to alter.

For reference, this technique is implemented by core in user.module (see user\_menu\_link\_alter and user\_translated\_menu\_link\_alter) and by menu\_token module.
> 11 votes

# Answer
If you install the Internationalization module, you will have language selection on your menu configuration page, for example, admin/structure/menu/manage/main-menu/add. Select the language and set the respective path for the language.

If you have two languages, you would need to create two menu items for each language. Then, if you select a language, the menu items with the respective language will be displayed.
> 4 votes

# Answer
After days of breaking my head over this I finally figured out how to solve my problem!!!

So, a little recap: I have three nodes that are translations of each other (with content translation).
Node 157 = English
Node 158 = Dutch
Node 159 = French

I needed a menu item that would dynamically show the correct node based on the interface language. But I couldn't create three seperate menu items, because this menu item has some child links to nodes that are translated with entity translation. Then I had some issues with showing the menu for the translions because these weren't in the menu. To make a long story short, here's the code I used:

**mymodule.module**

```
function mymodule_node_view($node, $view_mode, $langcode) {
    if($node->nid == 157) {
        if($langcode == 'nl') {
            drupal_goto('node/158');
        }elseif($langcode == 'fr') {
            drupal_goto('node/159');
        }
    } elseif($node->nid == 158 || $node->nid == 159) {
        menu_tree_set_path('main-menu', 'node/157');
    }
}

```

**template.php**

```
function mytheme_preprocess_page(&$variables) {
    if(!empty($variables['node'])){
        switch ($variables['node']->nid) {
            case 158:
                $variables['node']->title = '';
                menu_set_active_item('node/157');
                break;
            case 159:
                $variables['node']->title = '';
                menu_set_active_item('node/157');
                break;
        }
    }
}

```

If you can't make any sense out of this, feel free to ask me, I can hardly make any sense of it myself but it does the trick!
> 0 votes

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


title: Linking a pdf file within a paragraph

text:
# Question
Title: Linking a pdf file within a paragraph
I don't have Drupal installed on my computer (do I have to?). I access the admin site to make changes. I need to add a PDF file that describes an event. In order to do this quickly, I simply inserted some text describing the event, and at some point in the test, I want a link that people will click and the pdf file opens up.

I am totally clueless as to what I'm doing wrong. I typed `<a href= "/files/pdfdocname.pdf">` in front of the word I want linked. the link is active. However, it redirects to a page that says the page doesn't exist.

Is there another code I need to use? My document is found in the files folder of the root directory of the website.

# Answer
This is more of a general web question as opposed to being specifically Drupal related.

To answer your first question, no, you do not need to have Drupal installed on your personal computer in order to make changes to an existing site.

Here are a few things to check:

* The server could not locate your file. Double check your file path and URL to your PDF. If your PDF is located in the public directory (starting from your web site root) "sites/default/files", then the corresponding URL would be **http://www.example.com/sites/default/files/mypdf.pdf** If you type in your URL in your browser, it should load it up.
* If you are sure that you have the correct URL, but the PDF will not load up, double check the permissions on that file. Here is a good post about permissions: What are the recommended directory permissions?
> 1 votes

# Answer
First of all which Drupal version do you use?
In drupal 7 you have to enable "File" module (it's provided by drupal distr). Then go to content types (in Structure), add new content type or select on of exists. After saving content type see "manage fields". Add new field (fill label and field name), select Type of this = File, click Save. Then in extenstions fill pdf, and enter place of storing.
Then try create this content type, pdf file uploading will available and after saving you can see direct link to download it, if you don't see it, visit content type and check "Manage display" tab.
> 0 votes

---
Tags: navigation, files
---


# Question
Title: How to find the image cache url for images
I want to get the url to a specific image from image cache. I have the image file name (`my_image.jpg`), file path (`site/default/files/my_image.jpg`). From this value I want to get the url to a certain image cache folder (`sites/default/files/imagecache/240x135/my_image.jpg`). I cannot use any drupal methods/modules to get this because I am using external scripts to directly access the back-end database, from where I can get the image name, actual image path, but couldn't find the table where the url to image cache is stored.

How can I do this?

# Answer
You can always load Drupal API in your custom php All you have to do is copy the code from your index.php to your custom one or write

```
/** bootstrap drupal **/
chdir("/path/to/drupal/site/htdocs");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 1 votes

# Answer
You can use the `imagecache_create_url()` function:

```
$path = imagecache_create_url($presetname, $filepath);

```
* `$presetname`: String specifying an ImageCache preset name.
* `$filepath`: String specifying the path to the image file.
> 3 votes

# Answer
The way imagecache and drupal work is based upon the behavior that drupal is called into play only when a file is requested that doesn't actually exist. For example, if a user requests

```
/sites/default/files/imagecache/WIDTHxHEIGHT/foo.jpg

```

and it doesn't exist, drupal is booted up and a menu handler is called within imagecache which grabs the original `foo.jpg` and applies the WIDTHxHEIGHT preset and then stores the file back in place. Then the next time someone requests it, it does exist and the webserver happily sends it to the requesting user without getting drupal involved.

So... to your question, if you are using public files, eg:

```
/sites/default/files/foo.jpg

```

and have an imagecache preset of WIDTHxHEIGHT, the url of the file will be:

```
/sites/default/files/imagecache/WIDTHxHEIGHT/foo.jpg

```

eg, it is stuffing `imagecache/PRESET_NAME` after the basepath of your public file directory and before the file in question. If you had an original file:

```
/sites/default/files/avatars/USERNAME/bar.jpg

```

it would turn into

```
/sites/default/files/imagecache/WIDTHxHEIGHT/avatars/USERNAME/bar.jpg

```

Hopefully you see the pattern emerging. And thus nothing is needed to be kept in the database to do all of this.

Imagecache DOES however use permissions to allow/disallow users to use each specific preset, so, you can use them to stop users from requesting files that will never be used on your site by them manually surfing around to presets.

Hope this sheds some light on it all.
> 1 votes

---
Tags: 6, media
---


# Question
Title: Adding node edit links to a views block display?
I have a View with a Block display which shows 4 nodes of 1 type. I'd like to add node/xx/edit links to each node on the block. I've searched Google only to get confused more. Which hook to use? views\_pre\_execute, views\_pre\_render, views\_pre\_view .... And once you get the right hook, how do you actually add those links? Obviously I'd like to check the current user's `node_access` permissions too before adding those links.

This is Views 2 with Drupal 6.

# Answer
> 2 votes
There is a field called Node :Edit link which can be added to the fields and it will give you the edit link. This also respects the permissions that is it would only be shown to those who have permission to edit a post.

---
Tags: views, 6
---


title: openlayers toggle visibility of layer

text:
# Question
Title: openlayers toggle visibility of layer
I hope I'm not breaking any rules, but I wanted to cross-post this --- it is in the stackexchange for 'geographic information systems', but now I think the problem may be more on the Drupal side.

https://gis.stackexchange.com/questions/41223/openlayers-toggle-visibility-of-layer

I think the problem I'm having is in two things:

* I'm not sure how best to get a handle on the map object in jQuery.
* There seems to be a separate issue where strangely the click event is being fired twice.

EDIT: What I'm in effect trying to do is have the switchers below the map behave in the same way as the switchers in the right-hand-side grey switcher widget supplied by the openlayers library itself. See the screenshot.

I'm copying the question here, for the use of search engines etc.

I'm using OpenLayers in Drupal and am stuck while trying to make a layer toggle on and off (as it does from the right-side layer switcher).

See this map. http://dev.lambeth.coop/map

Click on food growing projects.

EDIT: I've changed the code to show the Drupal-specific elements.

```
(function ($) {
  Drupal.behaviors.openlayers_switcher = {
    attach: function(context, settings) {
      $(document).ready(function() {
        $('[id^=openlayers-switcher-block--]').click(function(e) {
          $(this).toggleClass('active');
          // 27 is the length of 'openlayers-switcher-block--'
          // layername is the string following that.
          var layername = e.target.id.substring(27);
          var ol = $('.openlayers-map').data('openlayers');
          var layers = ol.openlayers.getLayersByName(layername);

          // this doesn't work
          // if (layers[0].visibility) {
            // layers[0].setVisibility(false);
          // }
          // else {
            // layers[0].setVisibility(true);
          // }
        });
      });
    }
  }
}(jQuery));

```

When I try to toggle visibility - the visibility doesn't change.

EDIT: So it appears that the entire click function is being called twice.

I've tried putting these lines (in various combinations) at the beginning of the function, as these have been suggested in google searches for 'click events firing twice' etc.

```
$('[id^=openlayers-switcher-block--]').click(function(e) {
  e.preventDefault();
  e.stopPropagation();

```

... but these don't help - I still get the function called twice.

In any case, I'm new to openlayers and would be grateful for a way forward!

Thanks!

# Answer
@Duncanmoo: You're quite right, the response to this was incredible. It's nice to have the opportunity to explain how I came up with the current working solution.

The solution has a number of parts and is not entirely elegant, so feedback and advice is still very welcome!

Here is my custom drupal module:

https://github.com/LambethCouncil/opencouncil/blob/master/sites/all/modules/custom/openlayers\_switcher/openlayers\_switcher.module

The default html generated by openlayers for the switchers wasn't very easily changed with css, so I have hacked the openlayers.js file to give it some structure (for example wrapping each switcher in an anchor tag).

Take a look here for the amendments I made (search for lambeth.coop):

https://github.com/LambethCouncil/opencouncil/blob/master/sites/all/modules/custom/openlayers\_switcher/OpenLayers-2.11/OpenLayers.js

... a very important hack here was to add the click event to show/hide the layers (at time of writing this is line 2850):

// bind the click event to the aSwitcherBlock a element OpenLayers.Event.observe(aSwitcherBlock,"click",OpenLayers.Function.bindAsEventListener(this.onInputClick,context));

... this meant I could by-pass all the horrible jQuery problems I was experiencing and made me very happy!

... I would like to do the same with the openlayers-2.12 js file but got stuck. I'd love to find a way to do this - currently I'm stuck on openlayers-2.11 which is the old version as far as the Drupal Openlayers module is concerned. So that's a bit dumb.

Finally, see here for a method of taking the entire layer-switcher out of the default right-hand-side-of-map position and assigning it to a div outside the map:

http://drupal.org/node/1475316#comment-6945728
> 1 votes

---
Tags: javascript
---


# Question
Title: Possible to save plain text value when entity reference doesn't exist?
I have a user entity reference field. When I type in a name, but the entity/user doesn't exist I would like to save the name as a plain text value. Is this possible?

Thanks.

# Answer
Instead of adding an user entity field you can create a normal text field and then use formalter function to make it an auto complete.

The steps would be as follows.

Create a custom module.

First you would need to create a menu item to get the list of users to do that you can create a `hook_menu function`

```
function module_name_menu() {
  $items['userlist/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('you can define the permissions here'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

```

The next step would be to create the call back function.

```
function _module_name_autocomplete($string) {
  $matches = array();

  // Some fantasy DB table which holds cities
  $query = db_select('users', 'u');

  // Select rows that match the string
  $return = $query
    ->fields('u', array('name'))
    ->condition('c.name', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->name] = check_plain($row->name);
  }

  // return for JS
  drupal_json_output($matches);
}

```

The last step would be to create a form alter function to

```
function module_name_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_name']['#autocomplete_path'] = 'userlist/autocomplete';
}

```

This would change your textfield into an autocomplete field. you would also be able to enter any other name as well.
> 4 votes

---
Tags: 7, entities
---


title: Displaying Media as a field in Views?

text:
# Question
Title: Displaying Media as a field in Views?
I am trying to get Views to display files I have uploaded to my server using the Media module.

My end-goal is to display the 5 most recently uploaded pictures (from any album) in a slideshow on the front page (using Views Slideshow).

My website as a whole will be my personal photography-website when it's complete. The way I have everything set up so far is: I created a new content type for my pictures called *Photos*. Next, I create a new piece of that custom content and upload pictures to it. The organization structure is that, each new piece of *Photos* content behaves like an album--containing a set of images pertaining to it's title.

For example, if I wanted an album specifically dedicated to landscapes, I would create a new *Photos* piece of content, and upload all my images of landscapes to it.

The problem I have right now is, I can get Views to display my custom content type and scroll through it, but because each individual picture is wrapped inside a *Photos* content, the View will display every single image in that album 'per-slide'. How do I get Views to only display the five most recently uploaded Media files? (As opposed to what it's doing right now, displaying the five most recently added *Photos* albums.)

(Using Drupal 7)

# Answer
> 0 votes
In your field in your view, if you **uncheck the option "Display all values in the same row"** in the **"Multiple field settings"**, each new image in any photo piece of content will be considered as a row. You then will be able to show only the last 5 *images* instead of the last 5 *photo albums*.

# Answer
> 0 votes
Gregory has given you a good option.

Another option would be to use field collection instead of simple image field this way if you want you can add additional information to each image.

And when you create a view of the type field collection you can select the image field and also sort it using the **Field collection item: Revision\_id** that way you would be able to show the last fields. Or you can sort with **Field collection item: Field collection item ID**

---
Tags: 7, views, media
---


# Question
Title: Adding content to a database table during module install
I created a custom module and in the ".install" file, I create a table using hook\_schema().

I have about 90 error codes that I have to associate with an error message.

What is the most effective way to populate my table with those values during module install?

Thank you!

# Answer
As alternative of implementing `hook_install()`, if the module needs to be sure those data are present in the database before it runs, you can implement hook\_enable(). The difference between those hooks is that `hook_install()` is executed once, when the module is installed; `hook_enable()` is executed all times the module is enabled, which happens also when the module is installed. Using `hook_enable()` requires you to first verify the data are not already present in the database before to write them.
Implementing `hook_enable()` is what the Forum module does to create the taxonomy vocabulary, and the taxonomy reference field it uses. (See forum\_enable().)

Keep in mind that if you need to insert too much values in the database, then you should find another way to do it, as code taking too much time to be executed would cause a PHP timeout, and the code would not be complete the data insertion.
The alternative is using batch operations, or queue operations.
> 3 votes

# Answer
You have to insert the values using hook\_install()

From `hook_install()` API page:

> If the module implements hook\_schema(), the database tables will be created before this hook is fired.

Code:

```
function MYMODULE_install() {
  // DB Insert code here.
}

```
> 2 votes

---
Tags: installation
---


# Question
Title: Perform actions on field collection insert or update
I have created field collection and added it to my content type. I have created a node, and now user can add field collections on this node. But i need to write into a file(some stuff) when user `added` new field collection or updated it. I need something like `hook_node_insert` and `hook_node_update`, i cant find anything for field collection.

In preprocess\_node i have outputed `field_collection_field` and its returns only `ids`, and i can get them only by this code:

```
 $field_ids = array();
            //context_node = my current node,
            //field_block_id == field collection field
            foreach ($context_node->field_block_id['und'] as $element) {
                $field_ids[] = $element['value'];
            }
 $field_collection = entity_load('field_collection_item', $field_ids);

```

# Answer
A Field Collection Item is an entity, so the equivalents of the node hooks are `hook_entity_insert()`

> Act on entities when inserted.

And `hook_entity_update()`

> Act on entities when updated.
> 3 votes

# Answer
the field collection APIs are defined in the `field_collection.api.php`

The hook function that would interest you is hook\_field\_collection\_item\_presave()

```
/**
 * Acts on a field collection item being inserted or updated.
 *
 * This hook is invoked before the field collection item is saved to the database.
 *
 * @param FieldCollectionItemEntity $field_collection_item
 *   The field collection item that is being inserted or updated.
 *
 * @see hook_entity_presave()
 */
function hook_field_collection_item_presave(FieldCollectionItemEntity $field_collection_item) {
  $field_collection_item->name = 'foo';
}

```
> 3 votes

---
Tags: 7, hooks, entities
---


title: Override default page.tpl.php

text:
# Question
Title: Override default page.tpl.php
I'm trying to override the default page template for a specific page I created. I created a new page and then created a new template file called **page--node--1.tpl.php** and added the following code:

```
<?php
echo 'test?';
exit;
?>

```

I'm using 'garland' as a theme and it's still showing garland's template.

# Answer
Adding a template file to an enabled theme is like adding a hook to an enabled module: In both the cases, Drupal will not notice there is a new template file, or a new hook, as Drupal keeps that information cached.
After you add a new template file, you need to clear the Drupal cache, or disable the theme for then re-enable it. In the latter case, you forces Drupal to clear the relevant caches.

As side note, `exit` should be never used in a template file, not even for debugging. Doing so, you would interrupt Drupal when it calls theme\_render\_template(), with the effect that the template file would not be rendered.

```
function theme_render_template($template_file, $variables) {
  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  // The code after this comment is never executed, if the template file executes exit().
  return ob_get_clean(); // End buffering and return its contents
}

```

For debugging purposes, it's enough to print a specific string that allows you to know if the template file is loaded.
> 1 votes

---
Tags: theming
---


# Question
Title: Paginate views by first letter of Node title
I'm creating a View of staff profiles. It's a simple list of Node's Title filed (which happens to be the person's name. Instead of paging by number of items, I want to group them by first letter of first name. How should I start this?

# Answer
> 10 votes
Views comes with a nice default glossary view out of the box. Go to /structure/views/view/glossary/edit, enable it and set it to filter for your content type. viola.

And in case you are wondering where the Magic happens then you would find it in the contextual filter MORE options.

---
Tags: views, paging
---


# Question
Title: i18n + views, getting localized version of node
I have a view, lets call this **View A**, which only shows nodes - that are referenced as the 'hero' node to a taxononmy (one to one relationship). Additionally, I have another view, lets call this **View B** which does the opposite: only shows those nodes that do not have the hero relationship with a taxonomy.

Now I have translated all these nodes with the i18n module into two languages. But when I change language on the site the following happens:

View A stays the same, only showing the content in its original languages (in the language of which the relationships were created).

View B has the same content as it had, plus the translated 'hero nodes' that are supposed to be in View A.

I kinda gather this has to do with the relationship of node ids that is being filtered. However, how can I make this work that both View A and View B will show the appropriate localized content?

# Answer
> 2 votes
Add this to your Filter Criteria: "Content: Language (= Current user's language)."

---
Tags: 7, views, nodes, i18n-l10n
---


# Question
Title: Getting latest node to display as front page
I have what seems like a simple question about something it seems like many Drupal users would want to do, yet I cannot seem to find a good answer. I want my latest node (preferably of a single content type) to show as the front page. If I add a node, I want it to automatically become the front page. I don't want the front page to list nodes, etc. I found the "Top Node" module, which offers a view called "Single Node", which seems to do exactly what I want, but it has some problems (notably that it breaks the \<front\> alias used in setting block displays). There must be some way to do something that seems to be so common without an additional module, right?

I am aware that I could create a view that pulls the content from my latest node and creates a new page for it, but that seems like overkill, since the node already exists. Also, some of my node is being created programatically, and I cannot get those parts of the full node using a view.

How can I do this? Is there no built-in way?

# Answer
Your best bet is to use Views and attach a PAGE format. Then for display format: "full content". Its not overkill since your page would be cached anyways. But if your really not keen on using views, your best bet is to create a new tpl file for your theme and gear it towards the frontpage via: node--front.tpl.php (not sure if it was like that, but google it) Then return the latest node filtered by content type.
> 2 votes

---
Tags: 6, nodes
---


# Question
Title: WHERE can I change the notification email message for role assigments?
I'm using Ubercart 2 and Drupal 6 and I cannot find the place where I can change/customize the notification email that's sent out for new and/or expiring role assignments.

Here is the generic message:

> The role, member, you acquired by purchasing a product at our store has expired. Any special access or privileges that came with it are now gone. You can purchase it again by going to MY WEBSITE
>
> Thanks again,
>
> MY WEBSITE

I've looked under conditional actions, and while that helps me understand how and when emails are sent I cannot change the message text from there. Neither can I change the message text in `admin/store/settings/checkout/edit/messages`.

# Answer
> 0 votes
Per TR on the Ubercart forums:

"You may change this text under the Conditional Actions settings: /admin/store/ca/uc\_role\_notify\_revoke/edit/actions"

http://www.ubercart.org/forum/support/32739/where\_can\_i\_change\_notification\_email\_message\_role\_assigments#comment-70607

---
Tags: 6, ubercart
---


# Question
Title: Why does $form_state['input'] not correspond to the html of the form upon submittal?
I have a drupal form with repeatable fields allowing to type in as many phone numbers as one wants. Simplifying to the extreme, the code looks like this:

```
function form_test($form, $form_state) {
    $form = array(
        '#attributes' => array(
            'enctype' => 'multipart/form-data'
        ),
        'phoneNumbers' => array(
            '#type' => 'fieldset',
            '#attributes' => array(
                'class' => array('repeatable_container')
            ),
            '#tree' => true,
            0 => array(
                '#type' => 'fieldset',
                '#attributes' => array(
                    'class' => array('repeatable')
                ),
                'phoneNumber' => array(
                    '#type' => 'textfield'
                )
            )
        ),
        'enregistrer' => array(
            '#type' => 'submit',
            '#value' => t('Enregistrer'),
            '#submit' => array('form_test_enregistrer')
        )
    );

    return $form;
}

function form_test_validate($form, &$form_state) {
    drupal_set_message("<pre>" . print_r($form_state['input']['phoneNumbers'], true) . "</pre>", 'warning');
}

function form_test_enregistrer($form, &$form_state) {
    // Whatever
}

```

As you can see, the validation function simply prints out the phone numbers that are submitted through the form. The classes 'repeatable\_container' and 'repeatable' are used by the following javascript (simplified here) to allow the addition or reletion of phone numbers:

```
jQuery.noConflict();
(function ($) {
    "use strict";

    var getNextIdentifier, repeatButton, deleteButton;

    getNextIdentifier = function getNextIdentifier(original) {
        var re_lastNumber = /\d+(?!.*\d+)/, // One or more digits NOT followed by anything (.*) plus a number (\d+ : one or more digits). Basically, the last number of the string.
            m,
            newIdentifier = original;
        m = original.match(re_lastNumber);
        if (m !== null) {
            newIdentifier = original.replace(re_lastNumber, parseInt(m[0], 10) + 1);
        }
        return newIdentifier;
    };

    $.prototype.hasAttr = function (attrName) {
        var attr = $(this).attr(attrName);
        return (typeof(attr) !== 'undefined' && attr !== false);
    }

    $.prototype.increaseID = function (element) {
        return element.attr('id', getNextIdentifier(element.attr('id')));
    }

    $.prototype.increaseName = function (element) {
        return element.attr('name', getNextIdentifier(element.attr('name')));
    }

    $.prototype.increaseClassNames = function (element) {
        var classes = element.attr('class').split(' '),
            nbClasses = classes.length,
            i;
        for (i = 0; i < nbClasses; i += 1) {
            classes[i] = getNextIdentifier(classes[i]);
        }
        return element.attr('class', classes.join(' '));
    }

    $.prototype.increaseIdentifiers = function () {
        var attrs = [
                { attrName: 'id',           func: $(this).increaseID},
                { attrName: 'name',     func: $(this).increaseName },
                { attrName: 'class',    func: $(this).increaseClassNames }
            ],
            nbAttrs = attrs.length,
            i;
        for (i = 0; i < nbAttrs; i += 1) {
            if (this.hasAttr(attrs[i].attrName)) {
                attrs[i].func(this);
            }
            $('[' + attrs[i].attrName + ']', this).each(function () {
                attrs[i].func($(this));
            });
        }
        return this;
    };

    repeatButton = function (eventObject) {
        eventObject.preventDefault();
        var parent = $(this).prev(),
            element = $('.repeatable', parent).last(),
            clone = element.clone(true, true).increaseIdentifiers(true).appendTo(parent);
    };

    deleteButton = function (eventObject) {
        eventObject.preventDefault();
        $(this).closest('.repeatable').remove();
    };

    $('document').ready(function () {
        $('.repeatable_container').append($('<a href="#" class="repeater">+</a>'));
        $('.repeatable').append($('<a href="#" class="deleter">x</a>'));
        $('a.repeater').click(repeatButton);
        $('a.deleter').click(deleteButton);
    });
}(jQuery));

```

The problem arises when I create multiple phone numbers and I erase the very first one. For example, if I duplicate the phone number field and erase the first one, I would expect the validation function to obtain one phone number with id of 1 (the id 0 having been erased). But that's not what happens. In fact, what I get are two phone number, the first with id 1 (expected) and the second with id 0 (which should have been erased), in that order.

If I inspect the dom, I see that the javascript part works perfectly, so I'm pretty sure drupal is doing something here that I don't understand. Any clues on what's happening here?

# Answer
Generally, you can let Drupal handle more of this. I don't think I've ever had a need to touch $form\_state\['input'\], since $form\_state\['values'\] always holds user submitted data that is considered "acceptable" – e.g. if a user added an option to a `<select>` via javascript and then picked it, I don't want that value!

Of course, that means that you yourself can't add options or entirely new form elements via javascript, right? The solution lies in altering the $form on the server side and letting Drupal return the new markup the user via ajax. This markup *could* be the entire form, rewritten to have new or different elements based on some user activity, or it could just be a new `piece` of the form. This is done via the #ajax property on any form element (textfield, checkbox, button, etc.).

Consider this code:

```
function my_form($form, &$form_state) {
  // Wrap our form in a div with an ID that we know – this way we can
  // replace the entire form with a new version that has modified fields.
  $form['#prefix'] = '<div id="my_form_wrapper">';
  $form['#suffix'] = '</div>';

  $form['phone_numbers'] = array(
    '#type' => 'fieldset',
    '#title' => 'Phone Numbers',
  );

  // Use a custom property in the $form_state to track how many numbers we should allow.
  if (!isset($form_state['#num_phone_numbers'])) {
    $form_state['#num_phone_numbers'] = 1;
  }

  // Add as many phone number fields as the user has requested.
  for ($i=1;$i<=$form_state['#num_phone_numbers'];$i++) {
    $form['phone_numbers'][$i] = array(
      '#type' => 'textfield',
      '#title' => 'Phone Number ' . $i,
    );
  }

  // Button that has an #ajax callback which will be run whenever the user clicks it.
  $form['phone_numbers']['add'] = array(
    '#type' => 'button',
    '#value' => 'Add Another Phone Number',
    '#ajax' => array(
      'callback' => 'my_form_ajax_addPhoneNumber',
      'wrapper' => 'my_form_wrapper',
    ),
  );
}

function my_form_ajax_addPhoneNumber(&$form, &$form_state) {
  // All we need to do in this ajax callback is increase the number of
  // phone numbers that we want the form to include. By calling
  // drupal_rebuild_form() the original form builder will run again,
  // see the new count, and add an additional phone number field.
  $form_state['#num_phone_numbers']++;
  return drupal_rebuild_form('my_form', $form_state, $form);
}

function my_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['phone_numbers'] as $key => $phone_number) {
    drupal_set_message("Phone Number #{$key}: {$phone_number}");
  }
}

```

Note that not a single line of javascript is needed. Post any questions!
> 2 votes

---
Tags: 7, forms, javascript
---


title: Disable drag and drop/ Show row weights

text:
# Question
Title: Disable drag and drop/ Show row weights
The drag and drop screws up my theme when viewing it on a mobile device. Since this feature isn't necessary for my site can i completely remove these options to my users? I want to remove *all* drag and drop functionality.

Im using corolla Corolla 7.x-3.0-rc1.

This can be duplicated by viewing my site and dragging the window to be the smallest width. The drag and drop table does not adjust its width.

# Answer
> 1 votes
You'll want to alter `settings.tableDrag` to remove that drag and drop functionality, but I think what you're actually running into is a css rule that sets a width for the table.

---
Tags: 7
---


# Question
Title: Drupal 7 - Retain checkbox values across pages
In Drupal 7, I am using tableselect theme with PagerSelect to generate table with checkboxes and pagination. Any thoughts on how to retain checkbox values on pagination?

# Answer
Store the selected checked box in a database. Load each check box as the pagination goes and check the `#default_value`

example if I had 3 checkbox in a table select for my pagination:

```
$values = array();

$values[1] = TRUE;
$values[2] = FALSE;
$values[3] = TRUE;

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );

```

Obviously there is more to this, like pagination, but it should get you on the right track.
> 1 votes

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


# Question
Title: Problem with Aggregate CSS files option and tmp directory
This issue has been asked at lots of places and posts, but none of the solutions I found helped me.

I moved a dev site to a server where it is going to go live. Right away I was puzzled why I had to manually create a `tmp` directory at the site root to get it working at all.

On the dev site, I had been running with the `Temporary directory` set to `/tmp` (note the leading slash), but on the new hosting the site forces me to remove the slash, complaining about SAFE\_MODE.

The main problem though is that - even though the `tmp` directory is there and is writeable - turning on the `Aggregate and compress CSS files.` option causes the site to go into plain, no-stylesheet mode. The `Aggregate JavaScript files.` companion works just fine on the other hand.

I made sure the encoding of the CSS files is UTF-8 without BOM, as one of the posts suggested. Still - no go. Does anybody have a clue?

# Answer
As per Drupal PHP requirements, safe mode should be off.

It will interfere with file uploads and possibly email sending as well.

You'll probably find you need, in all the .htaccess places with:

`Options +FollowSymLinks`

to change to

`Options +SymLinksIfOwnerMatch`

In any case, if you can't disable PHP "safe mode" which, according to php.net is deprecated

> Safe Mode This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

and the other options don't work - you may need to consider using another webhost.
> 1 votes

---
Tags: files
---


# Question
Title: How do I get settings in admin/config/people/accounts/fields and admin/config/people/accounts/display into a Feature
How I would get admin/config/people/accounts/fields and admin/config/people/accounts/display into a Feature. I have been looking everywhere...

# Answer
For account fields, they will be listed under the 'fields' section just like any other. Just look for the fields that start with 'user-'.

For the view modes, I beleive you can export them to features by using the Dispaly suite module
> 2 votes

---
Tags: features
---


title: How to load a second user log in form?

text:
# Question
Title: How to load a second user log in form?
I have used default user login block on top navigation. I need to load another log in form on some pages.

I am trying to load the form by

```
drupal_get_form('user-login')

```

I get the following error:

> Notice: Undefined index: user-login in drupal\_retrieve\_form() (line 763 of /path/to/drupal/includes/form.inc). Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'user-login' not found or invalid function name in drupal\_retrieve\_form() (line 798 of /path/to/drupal/includes/form.inc).

Is it possible to load a second log in form? (Drupal 7)

# Answer
The key point in the error message is:

> ...expects parameter 1 to be a valid callback, function 'user-login' not found

You need to use:

```
drupal_get_form('user_login');

```

Where user\_login is the form builder function in this case.

e.g:

```
print render(drupal_get_form('user_login'));

```
> 3 votes

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


title: Changing text in Ubercart form

text:
# Question
Title: Changing text in Ubercart form
I am using Drupal 6 with Ubercart 6.x-2.9. In checkout, I dont need my customers to fill out their address - I just need name and email. So I have removed the address fields within the 'Billing information' part of the form.

When the customer gets to the 'Review Order' page, it lists the name and address with the label 'Address:'. As I only have the first and last name fields, I wish to change 'Address:' to 'Name:'.

Strangely, I cant seem to find anywhere where this 'Address' label is set (I did a text search in all files and searched through the database). Can anyone help please.

# Answer
> 1 votes
There is String Overrides

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

# Answer
> 0 votes
I found this which might help you change the name of the address field to name. The example is for first name but it shouldnt be too difficult todo the same thing for address. http://www.ubercart.org/forum/support/14998/problem\_uc\_get\_field\_name\_and\_translatation\_address\_text\_field\_names

```
function uc_get_field_name($field) {
$fields = array(
'first_name' => t('First name'),

to

function uc_get_field_name($field) {
$fields = array(
'first_name' => t('Test name'),

```

If this doesnt answer your question. I will alter my answer to accommodate your changes.

---
Tags: ubercart
---


# Question
Title: How to disable / modify AJAX validation on Hierarchical Select module?
I'm using the Hierarchical Select module for Drupal 7. In my form, there are also some required text fields. When I click the Hierarchical Select element to choose a value, several validation errors for the unfilled, required text fields appear above the HS element.

How can I prevent these validation errors from appearing?

# Answer
> 0 votes
You could try the brand new Simple hierarchical select module if it fits your needs. I used it and it's working great.

---
Tags: taxonomy-terms
---


# Question
Title: How to create a view type of Entity reference display?
I have an entity which contains a field collection of entity references and can edit the entity references with the ***Entity selection mode*** is Simple (with optional filter by bundle), but only *Entity Field Name x* shows in the list.

I also created a view which displays information from the referenced entity, but when I switch the Entity selection mode to Views I get the message:

> No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view

.

After that I created a number of views of the Entity Reference display type, which display the same information but error message still comes up.

Can someone show me the steps to creating Entity Reference display views? PS. I think what I am doing my be tricker than usual because the entity reference is a multivalued element in a field collection, but I am able t create views on it though\>

# Answer
Create a node view with the appropriate filters etc. you need to get the results you want to have in the reference field.

Then in the top left under the heading "Displays", Click "Add" and then select "Entity reference".

Then that display will be available to your field.

Edit: It doesn't have to be a node view, if you are referencing other entity types.
> 31 votes

---
Tags: views, entities
---


# Question
Title: How to pass data between operations of a single Batch?
Is there any way to pass data between operations of a single Batch, when using Batch API ?

for an example, say I have `$batch['operations']` as an array like this:

```
// Basic batch stuff to $batch here.
$batch['operations'] = array(
  array('my_initialize', $xyz),
  array('my_worker', $data),
);

// batch_set, process, etc.

function my_initialize($xyz, &$context) {
  // Can I process something here and pass it to
  // the operation 2 (my_worker) ?
  // May be some key in $context ?
}

function my_worker($data, &$context) {
  // How I can access some result from the my_initialize() function ?
}

```

I know I can set `$context['sandbox']` but that's related to a second call if I set `$context['finished'] = FALSE;`

I'm currently storing data (it's some kind of chemistry formula which is expensive to store in the operation itself or calculate before `batch_set`) in `$_SESSION` in `my_initialize` and unset it in finished function but I'm curious is there any better way to do this.

# Answer
> 15 votes
Thanks David for your answer. But unfortunately `$context['sandbox']` values were not retained through operations - they were retained through iterations of the same operation but not between operations.

Interestingly though, I found that `$context['results']` values were retained between each operation. I did a simple test using the following module:

```
<?php
function mytest_menu() {
  $items = array();
  $items['admin/content/mytest'] = array(
    'title' => 'mytest',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mytest_form'),
    'access arguments' => array('administer content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mytest_form() {
  $form = array();

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function mytest_form_submit($form, $form_state) {
  $batch = array(
    'title' => t('Working ...'),
    'operations' => array(),
    'finished' => 'mytest_batch_finished',
    'init_message' => t('Starting ...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'progressive' => FALSE
  );
  $batch['operations'][] = array('mytest_initialize', array('test data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  batch_set($batch);
  batch_process('admin/content/mytest');
}

function mytest_initialize($d, &$context) {
  dsm($d);
  $context['results']['test'] = 'inti val';
  $context['test']['test'] = 'init val';
}

function mytest_perform ($d, &$context) {
  dsm($context);
  $context['results']['test'] = uniqid();
  $context['test']['test'] = $context['results']['test'];
}

function mytest_batch_finished($success, $results, $operations) {
  dsm($results);
}

```

After the batch finished, I could see the `dsm()`'d messages. voilà: values were retained.

https://i.stack.imgur.com/tkAXx.png

It seems like only $context\['results'\] was given to the next operation. Arbitrary keys (`$context['my own key']` for example) didn't work.

Hope someone will find this useful :)

PS: \*previous not previos (screenshot).

# Answer
> 2 votes
Yes, you simply pass the data in

```
$context['sandbox'] = 'foo';

```

and it's preserved between requests.

---
Tags: 7, batch-operations
---


# Question
Title: How to store second dropdown value in database
```
function YOUR_FUNCTION_THAT_DISPLAYS_FORM(&$form, &$form_state) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();

  $options_state = array();

  // Using fetchAll() you can iterate through a result set.
  while ($state_record = $state_results->fetchAll()) {
    // You want state code as key, not state name as key.
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  // State form element.
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // City wrapper form element.
  $form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
  );

  return $form;
}

// AJAX callback function.
function _ajaxfunction(&$form, &$form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  while ($city_record = $city_results->fetchAll()) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,
  );

  return $form['city_element_wrapper'];
}

```

I have tried to get city value like this `'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city']`, but error is coming like

> Notice: Undefined index: city\_element\_wrapper in form\_test\_custom\_form\_submit()

How to solve it?

```
function form_test_custom_form_submit($form, $form_state) {
  $prog_id =1;

  db_insert('tot_prog')->fields(array('state1' => $form_state['values']['state1'],
'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],) // i have metioned like this,  is correct???? but its shows error, how to get the select city value???
        ->execute();
 drupal_set_message("successfully saved Settings");
}

```

# Answer
> 0 votes
Your error:

> Notice: Undefined index: city\_element\_wrapper in form\_test\_custom\_form\_submit()

means that index `city_element_wrapper` is missing in `$form_state` variable. Do this:

```
function form_test_custom_form_submit($form, &$form_state) {
  $prog_id =1;

  db_insert('tot_prog')
    ->fields(array(
              'state1' => $form_state['values']['state1'],
              'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],
            ) )
    ->execute();

  drupal_set_message("successfully saved Settings");
}

```

Always take the **reference** of `$form` variables if you want to fetch values from the variables or update the values of the variable. For more details about PHP reference read this.

---
Tags: forms
---


# Question
Title: Retrive $message variables in javascript file
I am using Drupal 7.

In the template file `page.tpl.php` there is a variable called `$message` which prints the messages like error, warning etc.

I want to access this variable in a JavaScript file. How can I do so?

# Answer
> 8 votes
In your page.tpl.php file:

```
$my_settings = array(
  'message' => $message,
);

drupal_add_js(array('my_settings' => $my_settings), 'setting');

```

Then in your JavaScript file you can access `$message` variable like this:

```
var message = Drupal.settings.my_settings.message;

```

Reference: The Drupal JavaScript API

---
Tags: 7, javascript
---


# Question
Title: Using multisite for a ReSTful API and Auth Strategy
# My Situation

I have a small app with a public interface. I'm interested in making an API for this to be used in a mobile environment and even eventually as a public API. I want to keep it simple with the priority on aspects like security and performance.

# My Plan

Why Drupal? Well, I know Drupal and I can envision a setup where I have 2 sites. www.mygui.com (default) and api.mygui.com (API). All database structure is determined by the work done in the **default** site. Using the Drupal Services Module (and only a few other necessary core modules) on the **API** site I plan to allow authenticated updates to the database by way of JSON and the drupal\_internal\_api.

# My Problem

I already have a prototype (not in drupal) that uses tokens. I'm new to services and don't really know all its limits and capabilities yet. This looks promising but still in the pipeline: Drupal Services Auth Token Module. I would like advice or resources regarding a good authentication strategy. For example, which is best? Keep the user base the same with assigned "API Uer" roles or have a completely separate user base specifically for the **API** site? Keeping in mind that an API username is a long term setup where the username/password or token should not change until the API user is ready with a new app release? Can I have a nice GUI for users to manage their **API** site credentials on the **default** site?

# Answer
This can certainly be achieved without any multisite. Meaning you could always house the API on the same site and proxy the path api.mysite.com to mysite.com/api thus allowing it to be invisible to the user. (Make sure your webhost supports mod\_proxy or you have some external proxy you can use for this task)

As for the actual authentication, I don't bother with tokens. Use credentials. This way people can get and keep a session (in line with however long you want them to based on session\_lifetime in your settings.php) - After an initial call to a log in path, they can then subsequently call the API over and over again by passing the unique session they are assigned.

Go with the single site approach and use web proxy magic to make it look like a different domain. Easy enough.
> 0 votes

---
Tags: users, services
---


# Question
Title: Should I use the Activity or Message module?
I want to create a view of user activity on my social site as shown below:

* User A is now following User B
* User C just joined "My\_Site\_Name"
* User D just gained 30 points for posting "User D\_Blog"

I have the user points modules installed for assigning points and other modules such as entity and tokens are also in place, along with rules. What i am not sure is which module should i use: the Activity module or the Message module. I first thought of using the Heartbeat module but its functionalities are all in the Message module as well.

# Answer
Heartbeat and Activity are both specifically intended for showing user activity (like on Facebook, Twitter, etc.)

Heartbeat is going to be deprecated in favor of Message. According to the Heartbeat module page:

> This project will be deprecated. The future would be in the module Message. It's much smaller and it cannot be compared to heartbeat when it comes to features. However the possibilities as API would be the same.

Note "the API possibilities are the same." This means that you will have to write custom code to get Message to do what you want, but as a result you will have more control than the Activity module.

Use the Activity module if you want a solution that works mostly out-of-the-box; use Message if you want to have a highly custom configuration.
> 3 votes

---
Tags: users, userpoints, status-messages
---


# Question
Title: Inquiring about finding mentors in the drupal community
Recently, I've noticed that drupal.org has added user profile fields for areas such as adding drupal ID's for attributing thanks to some mentors.

I was curious as to see if there currently is a means or process of seeking or finding a drupal mentor online or through drupal.org? I would ask people in person but i really don't know that many drupalers at the current moment.

Would the best place to look be the forums on Drupal.org? Or just persistent begging on IRC? I would eventually like to mentor others myself once i feel comfortable

# Answer
Welcome to Drupal! There are established core-office-hours for folks looking for mentorship (and looking to mentor); Your best best is to start there and outline your skill set. Someone will be more than happy to help. See http://drupal.org/core-office-hours \- So you don't have to beg in IRC. Just show up at the appropriate time. :)
> 5 votes

---
Tags: community-official-site
---


# Question
Title: Can't get generated content to push footer down
I have been hitting my CSS head against the wall for hours now. I'm not sure what I am doing wrong but I sure would appreciate some insight.

I've got a view that is populated by a content type that has an image and text. I've tried at least three sticky footer approaches and none worked.

We took bartik and modified the CSS as we've moved forward. I don't know if there's some css remnant of bartik wreaking havoc or my own CSS ineptitude. But we need to get it fixed and any help would be greatly appreciated.

Scott.

# Answer
First of all, never modify a core theme. Sub-theme. :) Second, the problem is that you are specifying "position:absolute" on some of your blocks which causes the CSS box-model to ignore any content inside the wrapper divs. When you write absolute, you are telling the browser: I know exactly where my content will be and so therefore you should ignore any flowing you want to do.

Try moving away from using position:absolute to position elements and instead use floats which will push the content region height and, in turn, your footer.

More info: http://www.w3schools.com/css/css\_boxmodel.asp
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: How to prevent Content type from appearearing in built-in Search results
I've got thousands of nodes which were created by importing using a Feeds module. I only want them to be searchable via the views search form, not by the built-in site search.

Is it possible to disable these nodes from being searchable by the built-in search, while still making it available to the search generated by a View?

# Answer
> 3 votes
There are two modules you can check out.

Search Config

> Restrict search results by the content type. This is a role based restriction.

Search Restrict

> Restrict by role who can search for each content type.
>
> Approach of this module is to re-write the search query, so that content is indexed and available as search results to users in role(s) that have permissions to view it, but not displayed to other roles.

OR

You can write your own query alter function.

```
function mymodule_query_alter(&$query) {
  $is_search = FALSE;
  foreach ($query->getTables() as $table) {
    if ($table['table'] == 'search_index') {
      $is_search = TRUE;
    }
  }

  if ($is_search) {
    $query->condition('n.type', 'node-type-name', '<>');
  }
}

```

And yes as webkenny suggested Custom Search as well.

> **Basic options**
>
> The module adds options to select:
>
> 1. which content type(s) to search,
> 2. which specific module search to use (node, help, user or any module that implements search),
> 3. advanced criteria
>
> For all these choices, there are options to switch between a select box, checkboxes or radio buttons, and also customize the selector label and the default - Any - text.

# Answer
> 1 votes
As we say in this community, "There's a module for that" - http://drupal.org/project/custom\_search

Good module to add-on if you're using the core search module. Won't affect your views in any way since those are two different flows.

---
Tags: views, nodes, feeds
---


title: Moving the Views header

text:
# Question
Title: Moving the Views header
I've enabled the Result summary in the Header for my view... However, it is being displayed at the top of the conetnt. I would like it to be display in between the search form and the search results. Is the only way to do this via a template?

The view is made up of nodes being imported using a Feeds module.

They are displayed in a table, and there is a search on top...

# Answer
I think using a template file will be the easiest way to do this.

In your view `=>` click `Theming information`

> =\> Select the tpl file that suits you best
>
> =\> place that tpl file in your templates folder under your theme
>
> =\> for the content of the file
>
> =\> under Theming Information in your view click `Display output`
>
> =\> copy that content to your tpl and change the position of your header
>
> =\> come back to Theming Information and click `Rescan template files` \- your newly added tpl(under your theme directory) should be highlighted(bold) now, which means you tpl is up and working!

Hope this helps.

\[I am sure you might know how to do all this, yet putting it in details might help somebody else looking for the same solution who hasn't yet learned how to :)\]
> 1 votes

---
Tags: views
---


# Question
Title: How to download the projects within a distribution using git, not just the distribution itself?
I've set `$options['package-handler'] = 'git_drupalorg';` set in my .drushrc.php file. Now when I run drush make for a distribution (in this case, the 7.x-3.x-dev release of Commons), the distribution itself gets checked out using git, but not the individual projects (modules and themes) within it. How do I also get those projects checked out as individual git repositories? I'm assuming submodules come into play, but what exactly do I need to do to get that working?

# Answer
> 1 votes
There's no direct way to perform this.

This is a sequence that may fit for a dev environment. It is based on `--package-handler=wget` and `drush make`. No submodules. Contrib is downloaded to `sites/all`.

```
cd /tmp
drush dl commons --variant=profile-only
drush make commons/drupal-org-core.make distro
mv commons distro/profiles
rm -rf distro/sites/all/
drush make --no-core --no-gitinfofile --working-copy distro/profiles/commons/drupal-org.make  distro/sites/all

```

I used `sites/all` because `drush make` wants a non-existent destination, so `distro/profiles/commons` is not an option. An alternative is to perform the last make in a tmp directory and copy over the `profile` directory afterwards.

---

As a side note, drupal.org profiles provide three packages to download: profile-only, core-profile-and-projects, profile-and-projects. See http://drupal.org/node/1867206 for reference.

`drush dl` provides an option to choose among these three tarballs: `--variant=<full,projects,profile-only>`. All three options are available for `--package-handler=wget` whereas for `git_drupalorg` the only valid option is `profile-only`, since it corresponds to a single git project.

That said, there's room to implement a more complex workflow to provide (`drush dl commons --variant=full --package-handler=git_drupalorg`) by using submodules.

---
Tags: version-control, drush
---


# Question
Title: Create a new region within an existing one
I want to create a new region within an existing region which is by default or is custom made. I have created a custom region called footer\_top. I want to create a new region within this region, i.e, a nested region. What should i do...what code should i write in page.tpl.php and how?

Thanks

# Answer
You can use the region.tpl.php

And add a template\_preprocess\_region to add the new region variable with in this region.

You can use the following code to add the region variable to the region.tpl.php

```
$variables['custom'] = block_get_blocks_by_region('custom');

```

So the over all process would be as follows.

first you would create a preprocess\_region function as given below

```
function theme_name_preprocess_region(&$variables) {
  $variables['region_name'] = block_get_blocks_by_region('region_name');
}

```

next you would create a region template file called region--region\_name.tpl.php

and print the variable `$variables['region_name'];`
> 2 votes

---
Tags: theming, 7
---


title: Call to undefined function

text:
# Question
Title: Call to undefined function
After creating the node (from a default and custom node) I received the following error,

```
Fatal error: Call to undefined function creative_customize_comment_form()
  in /home/MYSITE/public_html/includes/form.inc on line 1865

```

this happens for all users even admin.

# Answer
> 1 votes
I'm assuming `creative_customize_comment_form()` is a custom form function, so it probably exists in either:

1. A file inside a module that's not enabled, so Drupal can't find it
2. An include file in the module that's not automagically included during the page build.

The solution to the first is obviously to enable the module.

The solution to the second is to Make sure the appropriate file is included in the page build, using `module_load_include()`, e.g.

```
module_load_include('inc', 'creative_customize', 'creative_customize.pages');
// Now call drupal_get_form()...

```

Without more information I can't think of any other reason (other than the function name itself being incorrect) that `drupal_get_form()` would fail.

Source: https://api.drupal.org/api/drupal/includes!module.inc/function/module\_load\_include/7

---
Tags: nodes
---


title: Alert a message after ajax callback

text:
# Question
Title: Alert a message after ajax callback
With the code below I managed to alert the message but after that the form does not work properly, after the submit it redirects me to $base\_url/system/ajax and a json array is displayed.

```
$form['submitted']['test']['#ajax'] = array
        (
           'callback' => '_test',
           'wrapper' => 'nimportequi',
           'progress' => array('type' => 'throbber', 'message' => '')
        );

```

and the callback:

```
function _test($form, $form_state){
    $commands = array();
     $text = "";
     $alert = 0;
     if (valid_email_address($form['submitted']['email']['#value']) !== FALSE)
     {
        $result = user_load_by_mail($form['submitted']['email']['#value']);
        $text = ($result !== FALSE)?$alert=1:"Based on your email, you are not a member yet!";
     }
     else
        $text = "Based on your email, you are not a member!";
     if ($alert != 1 && $form_state['values']['submitted']['member'] == 1)
     {
        $commands[]=ajax_command_alert($text);
       // $commands[] = ajax_command_data("#foo", 'label_radio', '1');
     }
     $form_state['rebuild'] == TRUE;
     return array('#type' => 'ajax', '#commands' => $commands);
}

```

Also i am using a rule when the form is submitted. What am i doing wrong ? I cannot figure it out…

# Answer
> 0 votes
The problem was that i had a call like :

```
$form['#action'] = $_SERVER['REQUEST_URI'];

```

and this was causing that after second submit the variable will take the value:

```
$form['#action'] = 'system/ajax';

```

changing this to correct behavior solved my issue like below.

```
 if (!isset($form_state['values']))
    $form['#action'] = $_SERVER['REQUEST_URI'];
else
    $form['#action'] = $custom_url;

```

# Answer
> 3 votes
Add the ajax callback in the submit button of the form like this:

**Edit**

```
$form['radio_buttons']['#ajax'] = array (
  'callback' => '_test',
  'wrapper' => 'nimportequi',
  'event' => 'change',
  'progress' => array('type' => 'throbber', 'message' => ''),
);

```

This will ensure that when a radio button is clicked your ajax callback will be executed. Selecting radio buttons will give alert message, therefore the ajax callback should be applied to radio buttons.

Your ajax callback seems ok.

# Answer
> 0 votes
You need to set the '#ajax' on the select form element, not the submit.

eg.

```
$form['myselect'] = array(
  '#type' => 'select',
  '#options' => array(1, 2),
  '#ajax' => array(
    'callback' => '_test',
    'event' => 'change',
  ),
);

function _test($form, $form_state) {
  $commands = array();
  $commands[]=ajax_command_alert('testing');
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

---
Tags: forms, ajax
---


# Question
Title: How to auto publish images and news from email straight to a front-end portal?
I'm working for a daily newspaper with a news portal built on Drupal.

They require a way through which newsmen in the field can send images and news content to an email address. That image and content is to e auto-published straight to front-end of the portal.

Any suggestions about how to do so in Drupal?

# Answer
> 3 votes
You could use the mailhandler module for this. This would create a content from the mail send to an email ID

> Mailhandler takes mail (usually from an IMAP mailbox) and imports it as whatever type of content you choose. Plug-in modules allow you to do more awesome things like post comments, select different authentication methods, and set properties such as published / sticky status using "commands". Hugely powerful and flexible, but includes a "quick-start" module to help get you started.

---
Tags: nodes, emails
---


title: How to Table sorter in node page?

text:
# Question
Title: How to Table sorter in node page?
I have a table in node page. i have requirement to make it sort-able on click.

can anyone help?

# Answer
Try out these:
> -1 votes

# Answer
I used something like this in one of my installations:

```
// create a table of nodes of a specific content type
function MYMODULE_create_table($node_type) {
  // setup headers
  $headers = array(
     array('data' => 'Nid'),
     array('data' => 'Title', 'field' => 'title'),
     array('data' => 'Status')
  );
  // build query
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->limit(30);
  $query->fields('n', array('nid', 'title', 'status'));
  $query->condition('n.type', $node_type, '=');
  // make it sortable
  $query = $query->extend('TableSort')->orderByHeader($headers);
  // execute query
  $result = $query->execute();
  $rows = array();
  foreach($result as $node) {
    $rows[] = array(
       $node->nid,
       $node->title,
       $node->status
    );
  }
  // add a pager if needed
  if(count($rows) && ($pager = theme('pager'))) {
    $rows[] = array(
      array(
    'data' => $pager,
    'colspan' => 3,
  )
    );
  }
  // return html for table
  return theme('table',
            array(
                'header' => $headers,
                'rows'=>$rows,
                'empty' => 'No products found...',
            )
    );
}

```

The above perhaps work just as is, but it might give you some clue on how this can be done.

TableSort
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to place images in footer region through page.tpl.php
I would like to know how to place images in footer region through page.tpl.php. I know a block can be created and done so but i want to do so using page.tpl.php. Where should i write the code?

# Answer
If your not going to use blocks how about going a level deeper into the actual footer region template...

```
region--footer.tpl.php

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: Attaching a block to a view create with the User type
I have created a view using the User type. The view has 2 entity relationships to a location content type and a manager content type. With this I have setup contextual information relevant to the user's location and manager.

Now I need to add a generic video into the view as well. I have created a video content type and have it displayed using mediaelement.

My question is how do I add this content to my user type view? I am not sure if I am missing a really obvious way of doing this :p

I initially thought that I would be able to create a separate block view for the video then attach it to the original user view - but no luck there.

# Answer
The way I found around this is that in the the fields I added a Global View. Now the video is treated just as a field.
> 0 votes

---
Tags: views
---


# Question
Title: My ajax is altering form action/URL thus makes me impossible to read the $tid from it
I am using WEBFORMS which have as the topic taxonomy terms saved as hidden fields.

Unfortunate, after attaching files using Upload button this terms are lost ('No category'), as ajax is altering the form #action URL from

`/tid` e.g. `/19`

```
/file/ajax/submitted/file4/form-gTwVpNbQRszArGEUS1OfuwA8WgSLJOlcWGOuS6r9D5A

```

I have multiple file forms

From where to read $tid?

Therefore my $tid fail to load from URL

```
      function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

    if (strpos($form_id, 'webform_client_form_') === 0) {
        $tid = arg(1);
                  $term = taxonomy_term_load($tid);
                    if (!empty($term)) {
                        $category = i18n_taxonomy_term_name($term, $language->language);
                    } else {
                        $category = 'No category';
                    }
                    $form['submitted'][$category_fieldkey] = array(
                        '#type' => 'hidden',
                        '#value' => $category,
                    );

           // UP TO 10 FORM FIELDS
            for ($i = 0; $i <= 9; $i++) {
                $form['submitted']['file' . $i] = array(
                    '#title' => t('File'),
                    '#type' => 'managed_file',
                    '#description' => t('Please upload a document or image.'),
                    '#default_value' => variable_get('file' . $i, ''),
                    '#weight' => 100,

// ADD FORM SUBJECT
            $form['submitted']['subject'] = array(
                '#type' => 'item',
                '#title' => t('Subject'),
                '#markup' => '<div class="form-subject">' . $subject . '</div>',
                '#weight' => -100,
            );

                );
            }

    }
     return $form;
    }

```

# Answer
At the very end, you could use a variable\_set on if(!empty(arg(1))) and retrieve it with variable\_get on if(empty(arg(1))), but I'm sure there's a cleaner way.
> 0 votes

---
Tags: webforms, files
---


# Question
Title: Total number of nodes based on content type
I have 3 content types and I want to add a section to my site that displays the total number of nodes that each content type has.

However I don't want them to display per content type, i want the total number of all 3 to appear.

So basically nodes in A + B + C = total number of nodes

Is this possible?

# Answer
> 2 votes
In your views, section "OTHER", use **aggregation**.

It will provide you with options like COUNT in your views fields. You then can simply use the nid field, with a content type filter, and then display the count of the nodes.

---
Tags: nodes
---


title: "Page not found" on translated page

text:
# Question
Title: "Page not found" on translated page
I’m setting up a dual language site (English default / Chinese, Simplified) where Taxonomy translation mode is “Localize”.

I modified the Taxonomy term in Views.

I get results with preview in both default and translated language.

In page views, English is okay. However, Chinese page return “Page not found”.

I have tried Content: Has taxonomy term ID (translated) & Content: Has taxonomy term ID (with depth, translated) and a different validator "Taxonomy term (i18n)".

What did I missed? Please enlighten.

# Answer
> 0 votes
Did you set a chinese alias for your view page ?
Eg.: your view has an alias set to "my-listing" for the "EN" language.
=\> Try to set a chinese alias corresponding to "my-listing" alias, but for chinese...

---
Tags: taxonomy-terms, views, i18n-l10n
---


# Question
Title: Limit Entity Reference to Only Display Content Created By User
This might be an easy solution, but I can't seem to figure it out. I have a content type referencing another content type. I have the entity reference field in the cotent type, and wish to limit the display to only show cotent from the other content type that the user has created. Right now, it is displaying all the content created from the other content type.

# Answer
You can create a view to return only the content by the current user and then use that as the entity field reference.

You can select this form **ENTITY SELECTION**
> 6 votes

---
Tags: entities
---


# Question
Title: Reference node inherits taxonomy terms of referenced node
This is a problem that's been bugging me for days now and haven't yet found a solution in Drupal 7.

I'll be more specific:

I have a content type named Debate and another one called Vote. Vote type has a node reference field to Debate type.

Debate type has a term reference field (autocomplete widget, 4 values, Voting choices vocabulary) where user inserts the voting choices of his Debate node.

Vote type has a term reference field (select list, 1 value, Voting choices vocabulary) where user can choose a term to vote.

My problem is that the select list of the term reference field of the Vote node shows all the terms of the Voting choices vocabulary. What I want is the select list of the Vote node to show only the terms that come from the Debate node it's referring to.

In other words I need to filter out the terms of the Vote node based on the Debate node it's referring to, when I'm at the node/add/Vote form of course.

# Answer
> 1 votes
First you would create a form alter function and make the taxonomy field as hidden and add ajax functionality to the node reference field. I am assuming that then node reference field widget is a select list.

For the following example I am assuming your fields are in the Basic Page. you can change the function name to suite your requirement by changing the mymodulename and page.

I am assuming the field name of the term reference field is field\_vote and the node reference field is field\_debate

```
function mymodulename_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  // We add the ajax functionality to the node reference field.
  $form['field_debate']['#ajax'] = array(
    // #ajax has two required keys: callback and wrapper.
    // 'callback' is a function that will be called when this element changes.
    'callback' => 'vote_field_return',
    // 'wrapper' is the HTML id of the page element that will be replaced.
    'wrapper' => 'replace_vote_div',
  );

  // Add a wrapper around the taxonomy field.
  $form['#prefix'] = '<div id="replace_vote_div">';
  $form['#suffix'] = '</div>';

  // Check the form state to see if the debate field is filled.
  if (!empty($form_state['values']['field_debate'])) {
    // Load the debate node.
    $debate = node_load($form_state['values']['field_debate']);

    $form['field_vote']['#type'] = 'select';

    // Assuming the taxonomy field in debate content type is field_vote_debate
    // Some times the language for the field might be different from the language of
    // the node itself in this case you might want to look at a dump of the $date
    // field and make the required changes.
    foreach($debate->field_vote_debate['$debate->language'] as $vote_term) {
      $form['field_vote']['#options'][$vote_term['taxonomy_term']->tid] = $vote_term['taxonomy_term']->name;
    }
  }
  else {
    // Hide the taxonomy field to start of with.
    $form['field_vote']['#type'] = 'hidden';
  }
}

```

The call back function is pretty straight forward we simply return the field\_vote so that it can be rendered again in the form

```
function vote_field_return($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['field_vote'];
}

```

**Note: As per the comment Please find below the updated code if the node ID is coming from url**

I am assuming that the url to add the vote node is as follows

http://example.com/node/add/vote/23

where 23 is the node ID of the debate content type.

```
function mymodulename_form_vote_node_form_alter(&$form, &$form_state, $form_id) {
  // We use the arg() function to get the argument from the url. The numbering
  // starts from 0 and the one we need would be at 3.
  $debate = node_load(arg(3));

  // Assuming the taxonomy field in debate content type is field_vote_debate.
  // Some times the language for the field might be different from the language of
  // the node itself in this case you might want to look at a dump of the $date
  // field and make the required changes.

  foreach($debate->field_please_vote['$debate->language'] as $vote_term) {
    $term = taxonomy_term_load($vote_term['tid']);
    $form['field_vote']['und']['#options'][$vote_term['tid']] = $term->name;
  }
}

```

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


# Question
Title: Code Adding Additional Node Reference to Existing Node
I have 2 content types: video and product. Each product contains a node reference to a video, and products can be linked to multiple videos. I'm writing a custom module to add in lists of these products and videos from an outside URL with JSON. Loading the content into Drupal isn't an issue.

What I want to do is check to see if the product exists, and if so then to add an additional node reference to the loaded video. The JSON spits out an array of videos, and there's a product array within each video array (so 1-10 products can be linked to one video). Each product has a specific product ID I'm passing in, and with that I'm able to single out the product node that needs to be updated. I load the product node, and then instead of adding an additional reference, the code I have is replacing the node reference. I've tried a handful of changes which either alter nothing or throw an error.

Here's the code:

```
 $result = $efq->entityCondition('entity_type', 'node')
  ->fieldCondition('field_product_id', 'value', $prodID, '=')
  ->execute();
 if (!empty($result['node'])) {
   $nids = array_keys($result['node']);
   $node = node_load($nids[0]);
   $node->field_video['und'][0]['target_id'] = $node_id;
   node_save($node);
 }
 else
 {
   Add product node
 }

```

# Answer
> 0 votes
Found a solution, which was replacing this line:

```
 $node->field_video['und'][0]['target_id'] = $node_id;

```

With:

```
 $new = array('target_id' => $node_id);
 $node->field_video['und'][0] = $new;

```

---
Tags: nodes
---


title: set block to appear after page view

text:
# Question
Title: set block to appear after page view
This is probably a simple question, but how do you ensure a page view sites above a block on a page? Currently I have a page view which displays some content and then have a block view which holds some other content.This block view was added to the page view via the blocks page. Problem is the block appears before the page view content, any ideas on how to reorder this?

# Answer
If I understand the question right, the answer should be as simple as changing the block region : go to: https://www.example.com/admin/structure/block

and change the specified block region to footer or a region below "main content region".

You may check regions positioning by clicking on "Demonstrate block regions (Your-Theme-name)"
> 0 votes

---
Tags: views, blocks
---


title: View statistics with colorbox module

text:
# Question
Title: View statistics with colorbox module
So I'm building a community website for a local photography group and I'm trying to set up a "well equiped" group photo grallery that registered members can upload photos to. The gallery should include basic gallery features such as a view counter, to record how many people viewed a certain image. As well as the ability to comment on the photo.

I am a complete Drupal noob, this is my first Drupal project migrating over from WordPress because I believe Drupal has better flexibility and features as a CMS. I've created a view for our gallery, and am using the colorbox module for a stylish and professional presentation of the photos when clicked. I am also using the statistic module.

The road block I am at is that using the statistics module in partnership with the colorbox module image views are not being recorded. I believe this is because when you click on the image you don't actually navigate to the node, instead the image is pulled from the node and displayed in a colorbox modal. So, no matter the web traffic to the gallery and the photos being clicked or not, it always displays 0 views.

Is there a way to make it so when a image is clicked in the gallery and colorbox presents the image to the viewer it counts as a view?

The in-progress site I'm working on is beta.semiphoto.org The gallery can be found here. Please don't judge, I haven't addressed themeing and am still learning drupal. :-)

# Answer
You cannot since colorbox calls the image directly and not through a node page to register the hit. Your going to have to custom code in a js script. when an image is clicked it would report back to the server via ajax to record that hit per image.
> 0 votes

# Answer
For Downloads there's the Download Count module. But it Needs a Core Patch.

Here is a quote about it (from the module's project page):

> ... tracks downloads of private files attached to nodes via the core upload or contributed filefield modules for D6 and private core file fields for D7.
> 0 votes

---
Tags: views, nodes, javascript
---


title: Hiding admin (user/1) account

text:
# Question
Title: Hiding admin (user/1) account
How can I hide the main administration account from authenticated users? I have created a new role and created a new admin account.

# Answer
> 5 votes
You can implement hook\_menu\_alter() in a module to alter the access callback used for the "user/%user" path.

The code I would use is the following one, which is generic enough not to take assumptions about the access callback already set, and the arguments passed to that access callback. This means the code will work even if there is another module that alters the access callback for the same path.
The same code would work for Drupal 6, once you replace any occurrence of *user/%user* with *user/%user\_uid\_optional*.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user'])) {
    array_unshift($items['user/%user']['access arguments'], $items['user/%user']['access callback']);
    array_unshift($items['user/%user']['access arguments'], 1);
    $items['user/%user']['access callback'] = 'mymodule_user_view_access';
  }
}

function mymodule_user_view_access($account, $callback) {
  $args = func_get_args();
  // Remove $account and $callback from the arguments.
  unset($args[0], $args[1]);

  $uid = is_object($account) ? $account->uid : (int) $account;

  // 1
  if ($uid == 1) {
    // The user ID is 1; only that user can view that user account.
    return ($GLOBALS['user']->uid == 1);
  }
  // 1

  // Let the previously set access callback decide who has access to the user account.
  return call_user_func_array($callback, $args);
}

```

The code would not allow any user to access the super user account, except to the super user. If you want to allow the users with the permission to administer users to see that user account, you can replace the control statement commented with `// 1` with the following one.

```
  if ($uid == 1) {
    // The user ID is 1; only that user can view that user account.
    return user_access('administer users');
  }

```

# Answer
> 1 votes
The User One module looks like it may provide what you are looking for:

> Since Drupal 7 is more restrictive in allowing multiple failed logins, using different names (in 6.x version) is not needed any longer. These are the features of 7.x version:
>
> * User one account is protected from viewing and editing. Users -- even with 'Administer users' permission -- will be denied access.
> * ...

# Answer
> 0 votes
You can make hook\_menu\_alter to this menu to change permission

```
function hook_menu_alter(&$items) {
    $items['user/%user']['access callback'] = 'my_function';
}

function my_function()
{

}

```

# Answer
> 0 votes
You should be able to use Rules' "User is going to view a page" trigger to do this if you don't want to write your own module hook as well.

# Answer
> -1 votes
The easiest way to do that is to create a hook\_FORM\_ID\_alter

```
function legal_form_user_admin_account_alter(&$form, &$form_state, $form_id){
global $user;

  if($user->uid != 1){
    unset($form['accounts']['#options']['1']);
  }

}

```

---
Tags: 7
---


# Question
Title: How to exclude nodes with matching field values using EntityFieldQuery
This relates to a classified listings site, where nodes have an expiry date (date, field\_period, start/end = value/value2) and a notifications field (text, checkboxes, 336=two weeks, 672=four weeks).

We want to query for nodes which are going to expire between two and four weeks from now -

```
$period = 672;
$paid_date_max = date('Y-m-d H:i', strtotime('+' . $period . ' hours'));
$paid_date_min = date('Y-m-d H:i', strtotime('+' . $period/2 . ' hours'));

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'entry')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_period', 'value2', $paid_date_max, '<')
  ->fieldCondition('field_period', 'value2', $paid_date_min, '>=')
  ->fieldCondition('field_period', 'value2', 'NULL', '!=')
  ->addMetaData('account', user_load(1));
$result = $query->execute();

```

That works fine, but includes nodes which have already been sent a reminder (in which case field\_expiry\_notifications will contain a value matching $period). field\_expiry\_notifications may have multiple values, so we need to accept only nodes where NONE of the field\_period\_notifications values match $period.

Q: How to exclude from the above resultset any nodes with a matching expiry\_notifications value?

# Answer
> 2 votes
I believe you do need a subquery here. Apparently, you can actually do that with EntityFieldQuery. So first create your subquery, something like this:

```
$subquery = db_select('your_field_data_table', 't');
$subquery->addField('t', 'nid');
$subquery->condition('field_period_notifications', $period);

```

That gives you all nodes that *have* a matching value. Then add this to your EntityFieldQuery to exclude those:

```
->fieldCondition('field_period', 'nid', $subquery, 'NOT IN')

```

Or maybe you can do:

```
->entityCondition('entity_id', $subquery, 'NOT IN')

```

# Answer
> 1 votes
Sounds like what you need is an OR query (but also an AND); Look into altering the query after making it. This is probably the better explanation of that I've seen: http://treehouseagency.com/blog/fredric-mitchell/2012/02/21/or-queries-entityfieldquery

---
Tags: entities, database
---


# Question
Title: Path Auto Use Parent Tag, If it doesnt exist use current tag
OK. I have Pathauto and Token

I have the following Tag Structure:

Drinks \> Beer

I want to use path auto to make all nodes tagged with Drinks or Beer to have a URL of /Drinks/\[Node:title\]

So essentially I can use \[node:field-tags:0:parent\]/\[Node:title\] to get it to work correctly for all nodes tagged as Beer.

However if the node is tagged as Drinks then the parent does not exist and it will just return the node title. So in that case I would want to use \[node:field-tags:0:name\]/\[Node:title\]

So what I am looking for is something like this (if it exists):

\[node:field-tags:0:parent ELSE node:field-tags:0:name\]/\[Node:title\]

I have looked into custom tokens and can't figure it out. I was hoping there was a simple way to do this.

# Answer
Ok I figured it out. Use the Custom Token Module. Turn on PHP Filter in Core Drupal Modules Create a new Custom Token in structure Choose Nodeds in the Token Type then use this code:

```
<?php
if (isset($data['node'])) {
    $parent = token_replace('[node:field-tags:0:parent]', $data);
    return ($parent != '[node:field-tags:0:parent]') ? token_replace('[node:field-tags:0:parent]', $data) : token_replace('[node:field-tags:0:name]', $data);
}
?>

```

It will return the parent tag of the first tag in the list and if none exist it will return the first tag in the list
> 1 votes

---
Tags: taxonomy-terms, tokens, path-aliases
---


# Question
Title: CSS3pie - styles not being picked up in IE. How to reference the path?
I've downloaded and enabled the css3pie and libraries modules, and downloaded and extracted the PIE Library to sites/all/libraries/PIE

I initially tried adding the css selectors to admin/config/user-interface/css3pie but because that wasn't working I've now added them in my mysite.info: settings\[css3pie\]\[selectors\]\[\] = "#block-block-1" settings\[css3pie\]\[selectors\]\[\] = "#block-block-8"

In my css file C:\Projects\mysite\sites\all\themes\mysite\css\layout.css I've put the following:

# block-block-1, #block-block-8 {

```
background: red;
padding: 2em;
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
border-radius: 1em;
behavior: url(C:/Projects/mysite/sites/all/libraries/PIE/PIE.htc);

```

}

The PIE libraries is here: C:\Projects\mysite\sites\all\libraries\PIE\PIE.htc

What am I missing and doing wrong?

I have a feeling I've got the path wrong :(

Of course you will need to adjust the path to match where you uploaded PIE.htc in step 2. Note: this path is relative to the HTML file being viewed, not the CSS file it is called from.

How do I reference the path correctly?

# Answer
The PIE Drupal module should add the behaviour where necessary, you don't do that yourself. This would defeat the point of the Drupal module, and in using the Drupal module you don't need to specify the path yourself. (Though your current path there is incorrect, but I'm not sure on the correct way right now.)

css3pie can seem very touchy, there is a long list of known issues, some of which could be causing your problem. Also ensure that your files directory is writable, and that there are no errors on your sites status page. File permission problems can prevent the css3pie module from creating it's stylesheet. Each setting in the themes .info file should also be on a new line.
> 0 votes

---
Tags: 7, theming
---


title: Users in Database

text:
# Question
Title: Users in Database
If I update my Drupal 7 Production site (20 user accounts) from my Development site (1 admin user account) will I lose all the user accounts in Production?

I'm just going to transfer the files and export/import the database from Development to Production.

# Answer
> will I lose all the user accounts in Production?

Depends. If you replace the 'users' table, then yes, you will lose the accounts. You can use the Feeds module to easily import your users. That way you aren't overwriting the table itself.

Either way, backup, backup, backup!
> 2 votes

# Answer
You could also use phpmyadmin to export the users & users\_roles tables from the production database and import them into the development database, then you can do your update as usual.

Note: I'm assuming there is no risk to any other data referencing uid since you are replacing everything else.
> 1 votes

---
Tags: users
---


# Question
Title: How can I limit number of posts per day?
I need to limit number of forum posts that a user can create per day to, for example, 5 posts. How exactly can I do so using rules?

I know that there is a Node Limit Number module for this, but it ultimately needs to create rules, and I've got stock there.

# Answer
> 2 votes
Although not a solution for your problem with Node Limit Number, maybe one of these modules are easier for you to implement?

There is also a comparison of similar modules here.

---
Tags: nodes
---