# Question
Title: How to display specific blocks for specific roles alone w.r.t domains and subdomains
I want to display specific blocks for specific roles alone with respect to domains and sub-domains. I know i can give permission for roles in the block to be displayed.How do i differentiate anonymous users with respect to domain and sub-domains in the permission of roles. Help really appreciated.Thanks in advance:)

# Answer
> 0 votes
Hope this will help you,

In Drupal 7 you can use these modules

* Domain Context \- It allows administrators to set specific settings for each of their domains that are using the same code base.
* Domain Blocks \- Enables domain specific visibility settings for blocks.
* And for specific roles for each block you can select the roles. Go to your specific BLOCK configuration and select the **ROLE** in **BLOCK VISIBILITY SETTINGS**

---
Tags: 7, blocks
---


title: form set error is not working properly

text:
# Question
Title: form set error is not working properly
I am using Drupal 7

i am tracking login and setting errors but my error is not working properly

here is my code

```
  <?php

    function zloginsecurity_form_alter(&$form, &$form_state, $form_id)
    {
        switch ($form_id)  {
        case 'user_login':
        case 'user_login_block':
           $form['#validate'] = zloginsecurity_validators();
          break;
      }
    }

    function zloginsecurity_validators() {
        return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate','zloginsecurity_validate');
    }

    function zloginsecurity_validate($form, &$form_state) {
           if (empty($form_state['uid'])) {
            //Check user Track Record
            echo "hello";
     form_set_error('name', t('hello test'));
          }else {
              zloginsecurity_removeevent();
            //Delete Track Records for Particualr user
        }

    }

 ?>

```

it is not showing hello test, it is showing default message . Can anybody tell me how to solve this issue. simple echo is working

Thanks

# Answer
In `form_set_error`, the first parameter should be form name, if you are not sure of the name, just leave empty.

```
form_set_error('', t('hello test'));

```

This should work just fine.

**UPDATED ANSWER**

If you would like to have only your validation and skip the rest of Drupal core's validation for that particular form, you can unset the validator function and inject your own.

```
unset($form['#validate']);
$form['#validate'][] = 'zloginsecurity_validators';

```

Or

If you like to have both and give priority to yours first, then

```
$default_validators = $form['#validate'];
unset($form['#validate']);
$form['#validate'][] = 'zloginsecurity_validators';
foreach ($default_validators as $val) {
  $form['#validate'][] = $val;
}

```
> 2 votes

# Answer
Hope this will help you.

In Drupal 7, for validate and to set error you can use these code

```
/*
 * Implements hook_form_alter().
 */
function zloginsecurity_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_login':
    case 'user_login_block':
      $form['#validate'][] = 'zloginsecurity_validators';
      break;
  }
}
/*
 * Implements hook_form_validate().
 */
function zloginsecurity_validators($form, &$form_state) {
  if (empty($form_state['values']['uid'])) {//Check user Track Record
    form_set_error(**'[values][uid'**, t('hello test'));
  } //do your stuff here
}

```
\- You can **Delete Track Records** for Particular user in `hook_form_submit` by using $form\_state\['values'\] array;

Note : Make changes as per your requirement.
> 2 votes

---
Tags: 7
---


# Question
Title: How to get data from DB of 'testimonials' content type?
I have create a content type .i.e "testimonial",

This content type have two fields.

```
[1]field_data_field_testimonial_title
[2]field_data_field_testimonial_image

```

I have insert 3 records from admin, Now i want to retrieve all(3) records of "testimonial" content type.

But How?

# Answer
> 1 votes
You want to learn how to use the views module.

* You like the default front page view, but you find you want to sort it differently.
* You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
* You use /tracker, but you want to restrict it to posts of a certain type.
* You like the idea of the 'article' module, but it doesn't display articles the way you like.
* You want a way to display a block with the 5 most recent posts of some particular type.
* You want to provide 'unread forum posts'.
* You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

Views can do a lot more than that, but those are some of the obvious uses of Views.

---
Tags: nodes
---


# Question
Title: Programmatically create user in another Drupal site
How can I programmatically create user in another Drupal site?

The setup: multisite installation, userbase should be partially shared. Both websites have DB credentials setup in the `settings.php` file so I can query all tables from either site.

The problem: if I use `db_set_active()` to switch the database to the second site, calling `user_save()` will invoke all hooks of modules that are installed on the first site, not on the second one. This causes errors if the sites have different modules.

How can I avoid this problem? Any thoughts on workarounds?

Thanks!

# Answer
> 1 votes
One clean way to do this is using a web service with the services module. You could then expand to being able to create users through javascript or another server without direct access to that database.

It's easy to make your own resources to do exactly what you want.

It comes with native support for core functions, including registering users using the `user` resource. It's worth mentioning that the maintainers are happing to add new resources that support handling core functionality.

There's also other modules that extend services to provide single sign-on for example.

---
Tags: 7, users
---


# Question
Title: Authenticate joomla users to drupal website
I know this is not 100% drupal question but It might be the case that someone has StumbleUpon this one before.

I would like to give the opportunity for people having an account on a Joomla website to login to mysite and create a very basic account(automatically) when doing that. Something similar to facebookconnect.

Has anyone done this before?

One solution could be to use the connect module and find a way to expose the needed info on the joomla website.

# Answer
I'm not sure on a module based solution, but i would just add a custom form submit function on the user\_register\_form and then code from there. Success would depend on how you can remotely authenticate with Joomla.
> 1 votes

---
Tags: users
---


# Question
Title: How to create an unsubscribe link via mail in simplenews?
**UPDATE**

I updated my code to helderco's answer:

```
$mail = $form['mail']['#value'];
$subscriber = simplenews_subscriber_load_by_mail($mail);
$context = array(
    'category' => $form['newsletter']['#value']->name,
    'simplenews_subscriber' => $subscriber->snid
  );

```

but

```
debug(token_replace('[simplenews-subscriber:unsubscribe-url]', $context, array('sanitize' => FALSE)));

```

prints:

'https://mywebsite.com/newsletter/confirm/remove/'

is this correct?

---

I am writing a small module to extend the simplenews module, because as it seems, once a user has confirmed to be subscribed, no email is being sent. So I wrote a module which does exactly that.

Within the mail I am sending I would like to provide an unsubscribe link directly (or to a form). How would you do that? Simply adding the token within the mail text does not work.

```
<?php

function simplenews_apag_form_simplenews_confirm_add_form_alter(&$form, &$form_state, $form_id) {
  $mail = $form['mail']['#value'];
  $form['question']['#markup'] = '<p>'. t('Do you really want to subsribe your e-mail adress (%mail) to get a notification via e-mail as soon as ...', array('%mail' => $mail)) . '</p>';
  $form['#submit'][0] = '_simplenews_apag_simplenews_confirm_add_form_submit';
}

function _simplenews_apag_simplenews_confirm_add_form_submit($form, &$form_state) {
  simplenews_subscribe_user($form_state['values']['mail'], $form_state['values']['newsletter']->tid, FALSE, 'website');

  $path = variable_get('simplenews_confirm_subscribe_page', variable_get('site_frontpage', 'node'));
  drupal_set_message(t('Thank you very much for your interest. You will receive a confirmation mail.'));

  $params = array();
  $address_default = variable_get('site_mail', 'info@example.com');
  $params['from'] = variable_get('simplenews_from_address', $address_default);
  $params['to'] = $form_state['values']['mail'];

  drupal_mail('simplenews_apag', 'subscription_complete', $params['to'], language_default(), $params['from'] );

  $form_state['redirect'] = $path;
}

function simplenews_apag_mail($key, &$message, $params) {
  switch ($key) {
    case 'subscription_complete':

      $message['subject'] = 'Thanks';
      $message['body'][] = 'Bla Bla. Click the link beneath to unsubscribe: ';
      // how to provide unsubscribe function?
      $message['body'][] = '[simplenews:unsubscribe-url]';
      $message['body'][] = 'Regards';

      break;

    case 'unsubscription_complete':
      break;

    default:
      return false;
      break;
  }
}
?>

```

Any idea is greatly appreciated. I am using drupal 7

# Answer
You need to use token\_replace.

Try this:

```
<?php
$newsletter = simplenews_newsletter_load($node->nid);
$context = array(
  'category' => simplenews_category_load($newsletter->tid),
  'simplenews_subscriber' => simplenews_subscriber_load_by_mail($mail)
);
print token_replace('[simplenews-subscriber:unsubscribe-url]', $context, array('sanitize' => FALSE))';
?>

```

You should get a url like so: http://example.org/newsletter/confirm/remove/c453d5e25d2t10

That thing in the end is an hash, built in `simplenews_token()` (`simplenews.tokens.inc`).

**Update:** I updated my answer to show how you can get the correct variables from simplenews. Taken from `simplenews_node_view()` (in `simplenews.module`).
> 1 votes

---
Tags: emails
---


# Question
Title: Arranging related nodes in doubly linked list
I've an article and related stories. So I want users to navigate between the stories left or right or back to parent(the article).

Book module does it but when having 100's of books(articles) it could be cumbersome.

Is there any module in which I can create queues/groups which can be browsed much like book module based node pages? Nodequeue does not generate prev/next links and I don't think it provides what I want.

Any suggestions?

# Answer
> 0 votes
I've used the PrevNext module to accomplish a similar requirement.

Out-of-the-box functionality of this module would normally cover basic requirements in choosing the Previous and Next nodes such as:

1. Selection based on node `created` or `changed` date.
2. Selection based on node's `nid` field and `title`.
3. Additionally one has the ability to limit the previous and next to nodes of the same content type.

The nice part is that for any given node the previous and next nodes will be determined earlier and saved in the module's table by its own cron task (`hook_cron` implementation). Hence instead of determining the previous and next nodes (which could be costly in terms of time and space) while viewing a node and adding those to the page load a simple select query gets the predefined value.

Making call to `prev_next_nid` with your node id and operation as 'prev' or 'next' would provide one with the previous and next nodes' values which can themed to be displayed.

Additionally a hook `hook_prev_next_nid` is provided for developers to customize the function.

The caveats are that

1. if your logic for prev/next are not covered within the default functionality you might have to consider alternate means as there's not much option to cover such features as stated in the module's home page and
2. that the module showing up as dev version if you feel insecure by that status. However it seemed to work pretty well for me and appeared to be stable.

Note that the prev/next index will be cleared and rebuilt from scratch when user changes settings per a node type in the admin interface.

---
Tags: 6
---


# Question
Title: Add a class to the <body> tag on a node view
Is there any module that adds a field to all nodes and then add the value of that field as a class on the tag of the page when the node is displayed?

# Answer
This is quite simple and could likely be done in `template.php`. I would start with the following:

1. hook\_preprocess\_html() to hook into the rendering of the `<body>` tag.
2. menu\_get\_object() for loading the current node (in some themes it might already be present in `$variables` as `$variables['node']`).
3. Grab the data the user entered into the field using `field_get_items` or something similar.
4. Pass it to `drupal_clean_css_identifier` to ensure it's ready to be used as a class.
5. Add it to the end of the `$variables['classes_array']` variable.
6. Clear the cache to ensure your new hook is picked up.
> 2 votes

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


# Question
Title: Custom module shows in list but not in permissions
I have a simple module I created and it shows up in modules config panel and I have enabled it. The functions are called and the output even shows:

```
function products_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('Products Help');
  }
}

function products_perm() {
  return array(
    'access products' => array(
      'title' => t('TBYT Products'),
      'description' => t('Administer TBYT Products'),
    )
  );
}

function products_menu() {
  $items = array();

  $items['products/winnipeg'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping in Winnipeg',
    'page callback' => 'list_products',
    'access arguments' => array('access products')
  );

  return $items;
}

```

What am I missing? I cannot find this module anywhere under permission configuration...I expect to find the option for allowing "access products" to authenticated user???

Any ideas?

# Answer
> 0 votes
**You missed this one**

```
'access callback' => 'user_access',

```

If you give this one in the `hook_menu` then it will show in the permissions tab.

\[Updated Answer\]

`Hook_permission()` will allow you to create a permission string in the permission tab.

```
    function hook_permission() {
  return array(
    'string' => array(
      'title' => t('Administer my module'),
    ),
  );

```

}

# Answer
> 1 votes
You need to implement hook\_permission to register any custom permissions that your module exposes.

Once you have implemented this hook you can then use your new permission in `user_access` or `hook_menu`.

---
Tags: 7, users
---


# Question
Title: Cant display error message in custome form!
I have create one form which have two fields.

```
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#maxlength' => 20,

    '#required' => TRUE,

);
$form['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#maxlength' => 20,
    '#required' => TRUE,
);

```

In page.tpl.php file displayed both fields. Now i have press submit button without enter any value in text box error message will displayed.

But in my page.tpl.php file cant display error message!

How can i show all error message?

# Answer
Hope this will help you.

In Drupal 7, just add this line in your **custom template** file

```
<?php if ($messages): print $messages; endif; ?>
```
> 2 votes

---
Tags: 7
---


# Question
Title: User picture not showing, after moving from localhost to prodution
I have moved my site from localhost to the web hosting, and in the web hosting, the user picture have been lost and the users cannot upload new photos. But in the localhost everything was working nicely

When i inspect the "lost picture", i get this path: `MY_SITE.com/sites/default/files/styles/thumbnail/public/pictures/MY_PICTURE-5-1375807631.jpg?itok=eQN27TLT`

I'm getting crazy with this. Is there any sugestion? Thank you

# Answer
That may be due to permissions issues for your files floder. Try giving permission to your `sites/default/files` folder.That will resolve your issue.
> 0 votes

# Answer
You might find that updating the permissions on your files folder is necessary. Depending on your server configuration you may need to run `chmod -R 770 ~/public_html/sites/default/files` (assuming the path to your files folder) or use `777` as your permissions string.

Beyond that, ensure that when you moved to production you deployed an entire copy of the site including all the files.
> 1 votes

---
Tags: users
---


# Question
Title: I want to change language in a select list and whole site changes to selected language(All content)
I want to have four languages Catalan, Spanish , French and English. English language will be default.If i change language to be spanish,i want the whole site to change to spanish or if i change to french the whole site should changed to french.

Example site. I want to know how this would have been done ?

Any help really appreciated :)

# Answer
> 0 votes
I don't believe you need Internationalization module, core's Locale module will already do the job. It makes content translatable, so yes you need to translate it manually. When you enable Locale and edit a node, the option to enter a translation will appear.

# Answer
> 0 votes
if i where you i would use google translate for websites its very easy ......go to google webmaster tools choose google translate for site take add your site domain and generate the code ...then take the first code and put it in the page.tpl.php in the header section and take the second code and put it after the directly and at then you should have 52 language on your site all the site is translated to your selected language and you could limit it to any no of languges from the webmaster tool before generate the code and inject it to your page.tpl.php

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


# Question
Title: Getting pages defined by taxonomy to display in a view
I have a page view that displays video thumbnails in a grid layout (three columns.) Above each thumbnail is the title of the video and below it is the category. The category is defined by taxonomy and selected by the user when he uploads his video.

The overall view (all videos regardless of their category - ex: /videos/all) displays nicely in a page view (no taxonomy term involved here.)

The display problem arises when a user selects a category. Although the items belonging to that category are properly filtered, I cannot get a view (ex: videos/movies) to display them in the same manner as the overall view (three columns.) I get instead the node teaser layout (thumbnails in one column with a "read more" link below each. A page view with the same path as the corresponding taxonomy term (ex: videos/movies) does not take control of the display.

How can I solve this and have all category views display like the videos/all page? Display Suite does not "see" the videos/movies page created by taxonomy.

Any and all help will be greatly appreciated. Thank you. :)

# Answer
> 1 votes
Hope this will help you,

In Drupal 7, you can use Context module.

* Context : It allows you to easily organize your site into manageable sections .
* Create a **new** context using the **path - videos/%category** and arrange the items like **Overall View**.

Note : Context

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


# Question
Title: How to change the place of a block or region based on url path?
I have a menu block and it will be displayed on all pages, but I need to change the placing of it. On certain pages (dependent on path) I need to display it above the main content, while on other pages I need to place it below the content. I am experimenting with the context module and I was able to put the block above the content, but then on these pages, the menu shows BOTH above and below the content.

I have a solution in mind, but there must be a better way: I can set up two regions, one above and one below the content, then put the menu block in the region below the content, and set up a context to put the menu in the above region AND hide the below region. This could work, though I think there should be a more elegant way.

# Answer
Hope this will help you.

In Drupal 7 you can achieve it using Context module as suggested by the Jack.

Steps

* Fist of all disable the **menu block** using `admin/structure/block`.
* As you specified you need to show **menu block** in two regions, then those 2 regions(**main content** and **above the content**) must exist. If not then create it.
* Create a new context and add **menu block** based on your requirement and path.
* Showing **menu block** block in region **Content**
* Showing **menu block** block in another region **user bar second**

Reference :
> 1 votes

# Answer
You can add the URL check logic in your theme's template.php (use theme\_preprocess\_page hook) and pass the result (something like $variables\['isBlockAboveContent'\]) to the page.tpl.php and render the block where you need after checking the $isBlockAboveContent .

Hope this helps.
> 0 votes

---
Tags: blocks, 7
---


# Question
Title: Modify form elements based on current select box value in same form?
I'm writing a custom module and I have a select box in a form with two values, Test and Production. I want to remove a specific fieldset from the form if Production is selected, and add it back if Test is selected. Is there a straightforward way of doing this?

# Answer
Certainly, you can utilize the `#states` setting. Information can be found in the Drupal Forms API as well as in the drupal\_process\_states() API where you can see examples and documentation on how you can toggle your fieldset based upon the value of that select box.
> 1 votes

---
Tags: 7, forms
---


title: Create a list field linking to PDFs

text:
# Question
Title: Create a list field linking to PDFs
I'm relatively new to Drupal 7 and I'm a little lost on this one.

I have an "event" Content Type that contains a list field type that displays about five "location" options. Here they are, in key|label form:

Main Entrance|Main Entrance

School Entrance|School Entrance

Park Entrance|Park Entrance

Staff Entrance|Staff Entrance

What I'd like to do is directly link each label to a PDF file containing a map of the entrance location; e.g., `Staff Entrance|<a href="filepath">Staff Entrance</a>`.

When I try to customize the field settings, Drupal tells me that the following tags are allowed in labels: `<a> <b> <big> <code> <del> <em> <i> <ins> <pre> <q> <small> <span> <strong> <sub> <sup> <tt> <ol> <ul> <li> <p> <br> <img>`. But in spite of my efforts to add tags to labels, Drupal changes them to HTML entities and ignores them; e.g., `<Staff Entrance>`. This is the case for all HTML tags.

Is there a reason HTML is not rendering in my labels?

Thanks!

# Answer
> 0 votes
My guess is that a label can't be an anchor (because of XSS). You may want to use theme\_preprocess\_field or theme\_preprocess\_node to wrap the label with an anchor.

---
Tags: entities, files
---


# Question
Title: Simple button to send users info to an email address
What would be the best route to create a button on a page that once it's clicked, it sends an email to the administrator. Basically we are using the profile percentage completion module, and when a user is at 100% I want to display a button to opt into a program (the program meaning, it sends us all of their info in their drupal account)

It seems very simple, but I can't wrap my head around this. I could definitely add the logic to where if the profile is 100%, it will display a button. It's just the button functionality that I don't know how to do. Would I write a ajax hook? create a custom module?

Any help would be appreciated!

Thanks!

# Answer
Hope this will help you.

In Drupal 7 you can use **ctools** for your requirement.

* Just create a **ctools link** after 100% of profile completeness

Steps

* Create link on 100% of profile completeness in the profile page

```
global $user;
ctools_include('ajax'); // Include the CTools tools that we need.
$entity_type = 'user';
$bundle = 'user';
if (module_exists('pcp')) {//check for 100% completeness
  $check_percentage = pcp_get_complete_percentage_data($entity_type, $bundle, $user);
  if (is_array($check_percentage)) {
    if ($check_percentage['current_percent'] == 100) {//100% of profile completed
      $mail_link = '';
      $mail_link = ctools_ajax_text_button(t("Send Mail"), "send_mail/nojs/$user->uid", t("Send Mail"));
      $link = "<div id='#send-mail-" . $user->uid . "'>"; //must have unique ID for replacement
      $link .= $mail_link;
      $link .= "";
    }
  }
  return $link;
}

```
* Create menu for callback

```
$items['send_mail/%ctools_js/%'] = array(
  'title' => '',
  'page callback' => 'send_mail_link',
  'page arguments' => array(1,2),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);....
 return $items;

```
* Send mail callback

```
function send_mail_link($js, $uid) {
  // Include the CTools tools that we need.
  ctools_include('ajax');
  $output = '';
  if(isset($uid)){
     $output .= '<span class="mail-sent">Mail Sent</span>';//without link
    //Code for sending an email to the administrator
    if(/* mail sent */){
       drupal_set_message('mail sent');
    }
  }
  if ($js) {
    $commands = array();
    $commands[] = ajax_command_html("#send-mail-$uid", $output);
    print ajax_render($commands);
    exit;
  }
  else {
    return $output;
  }
}

```
> 3 votes

---
Tags: hooks, ajax, emails, users
---


# Question
Title: Pulling capacity and slots left from entity registration
I'd like to pull the values for capacity and the slots left from a registration created by the entity registration module. This sets up registration entities which are attached to (I believe this is how it works - my familiarity with the entity system is only so-so at this point, but I'm actively learning) nodes.

I'm creating a view for the event nodes, I would like to display these fields - how would I go about doing that? Would I create a relationship of some sort in the view?

What's the standard method to pull another, related entity's content into a node entity?

# Answer
> 0 votes
I managed to solve this by pulling in the relationship of "Registration Settings: Node to Registration Settings" and putting the fields for total as well as used slots in.

In addition, when needing to calculate the amount of remaining slots, I calculated this with views php.

---
Tags: views, entities
---


title: Adding Link To Drupal 6 Views Slideshow

text:
# Question
Title: Adding Link To Drupal 6 Views Slideshow
Probably a stupid question. I'm more used to Drupal 7, but I'm working on a new site today and it's Drupal 6. There is a Views Slideshow on the home page. The buttons and images automatically cycle. We want to add a link to each button/image so people can click and go to a related page.

http://simulab.com

I looked at the nodes for the content used for each image and I was surprised that there is no field to store a link--as is common in most slideshows I see now.

The Links module is installed, but again there is no Link field type in the node content used to store each image/button in the view.

Looking at the HTML, I see that there is no href for each button or img. Apparently one can hover over a button to switch visible images, but cannot -click- to go to another URL.

What's the preferred way to add a click URL to each of the images and/or buttons in the view?

TIA

# Answer
> 1 votes
* Add a `link` field using CCK for the content type.
* override the label output to include the rendered link in the View.

---
Tags: views, navigation, javascript
---


# Question
Title: Add a remove item button on checkout page
i have an express-checkout page and the cart is shown but i have to give the customer the chance to remove items from his cart at this stage.

i edited the view `Shopping cart summary (Commerce Order)` by adding a `(Line Item) Commerce Line Item: Delete button (Remove)`

now when i click that button the form-validation starts and the item wont be removed. any chance to fix this? a multistep-form is not an option for me.

# Answer
This is a pretty common support request, and the gist of it is you cannot use Views form functionality on Views embedded in the checkout form. The reason is pretty simple to understand - you end up nesting a FORM tag within a FORM tag because Views doesn't know that it's building form elements to render inside another form. The solution is not so simple.

The best advice I've been able to give thus far is to disable the cart contents checkout pane and create a Views block instead that uses the form functionality. However, if someone removes an item from the cart after making a change elsewhere on the page, the page would refresh and that data would be lost. Thus you'll want to figure out a way to have that remove button work via AJAX, which is totally possible through the forms API but remains undocumented as far as I know. If you do code a solution, a blog post about it or doc page on d.o would be great.
> 2 votes

---
Tags: 7, commerce
---


title: Changing CSS in Zen Theme in Drupal 7

text:
# Question
Title: Changing CSS in Zen Theme in Drupal 7
This is another question that I am sure is very simple. I've been working through tutorials on setting up a Drupal site from scratch with the Zen Theme. I have my Sub-Theme working just fine, thanks to https://drupal.org/node/1549668 and http://drupalonlinetraining.com/youtube/linwclark/drupal-7-basic-theming-zen-and-css

Now, I want to edit the CSS. Unfortunately, the documentation that I can find references 25 separate stylesheets (including both of these tutorials and this page.) The version I have, however, has far fewer sheets than that (13 according to the ReadMe).

I did find the ReadMe that describes the new stylesheets, but as this is my first foray into CSS within Drupal, I'm still a little unsure as to where I should start to add styles. Is it in normalize.css? Is this where I would add, for instance, a background image?

Thanks for any help, and/or for pointing me to a tutorial that breaks it down for the latest version of the Zen Theme!

# Answer
You should just focus on several main Zen css files:

* **blocks.css** : should add the css of blocks that you create from backend or from your modules.
* **forms.css**: should add the css for forms: for example: login form, register form, contact form (from contact module)
* **pages.css**: should add the css for the pages: static page that you create from Drupal backend or views page..
* **nodes.css**: should add the css for just the common structure of node and specific nodes also
* **tabs.css**: should add for the tab style (You can easy see the tab style at user login page with login/register/forgot password).

For Zen theme. I suggest you should understand SASS structure and change the scss files instead of css files and the name of scss files are the same as the list above (like blocks.scss, pages.scss, nodes.scss, tabs.scss). You should check Getting started with Drupal7, Zen, Sass and Compass for doing your current stylesheet.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Views is not linking images to content for anonymous users in Commerce Kickstart
I'm having this problem:

I'm using Commerce Kickstart 7.x-1.19 (also tryed on 2.x) and I'm trying to create a simple view to replace my homepage with a list of products, set the relation to the referenced prodcut etc. Everything is working as expected except for images that are not linked to content (node display) for anonymous users.

I know that the image formatter must be changed on Product Type -\> Manage Display and not in the content type itself.

If I change a settings in the on the View I'm working, I can set any Image Style and is rendered as it should be, even Color box is working as expected for every user, but for some reason when I choose any Image Style and set Link image to: content this is not working, the image is not linking to the node.( Field title does link to the content)

I think this is a permissions issue because when I was setting this view I had this problem: Views results empty for unprivileged user when using Relationship (https://drupal.org/node/1276450), I fixed that using the permission View any product of any type.

Any help or idea is very appreciated, this is driving me crazy...

Thankyou

# Answer
> 0 votes
I was having the same issue and was discussing this in an issue ticket for Drupal Commerce. Here is what I found:

> It is extremely unclear how to display products using Views. After much googling, I had settled on creating a View displaying either `CONTENT` or `COMMERCE PRODUCTS` displaying `FIELDS`. I would then add a `RELATIONSHIP` to `CONTENT: REFERENCED PRODUCT`. This worked and it was easy to add fields and get the output exactly how I wanted it. The problem, and the reason I reopened this ticket, is that the `COMMERCE
>  PRODUCT: IMAGE` field would link to the admin display, not the product display.
>
> The problem was what I chose to display when creating the View. First, I updated Commerce Kickstart, which broke all my existing Views with a SQL error. Then I installed a fresh Commerce Kickstart to test product display views. There were numerous issues with the install, one which broke the front page. No idea. But through testing the fresh install, I stumbled across the idea to study the `COLLECTION` view that comes with Commerce Kickstart. I noticed that it was displaying `PRODUCT
>  DISPLAY` content, and a field of `CONTENT: RENDERED ENTITY` with the `PRODUCT LIST` view mode.
>
> Long story short, I discovered that by using Display Suite, I could create custom view modes, which would be customized with the exact fields I wanted to display. This had to be done on both the `CONTENT
>  TYPE` (product displays) and `VARIATION TYPES`. While `MANAGING
>  DISPLAY` for the type you are editing, select the tab at the bottom labeled `CUSTOM DISPLAY SETTINGS` to enable the custom view mode made in Display Suite. Then you can select the view mode for the content types and change the fields available. Its a bit tricky to figure out where to change what values (in `CONTENT TYPES` versus `VARIATION
>  TYPES`) but I'm sure most people can figure it out.
>
> After you create your `VIEW MODE`, create a new View that displays `PRODUCT DISPLAY` items, not `CONTENT` or `COMMERCE PRODUCTS`. Then make sure you are using `RENDERED ENTITY` either for the whole node or in a field (where it will be listed `CONTENT: RENDERED ENTITY`). Under the `RENDERED ENTITY` settings, select the `VIEW MODE` you created, and viola! It outputs the fields you want AND links to the content not the admin page. What it outputs will require some CSS styling, as there are more default drupal styles applied to the rendered entity than just plain fields. But that can be tweaked in the Views settings themselves or by using Mothership Base theme.

This is from my original post is on Drupal Commerce Issues.

Hope this helps! :)

---
Tags: 7, views, users, media, commerce
---


# Question
Title: How do I modify the teaser products display page in Kickstart Commerce?
How do I modify the teaser products display page in Kickstart Commerce?

I would like to display smaller product teasers with a "four column" layout versus the default "three column" layout. Is this a task for "views"? Modifying some "css" file? Both?!

Any direction on this would be huge help.

Thank you!

Tom

# Answer
You'll want to look into Display Suite. Its a great module which allows you to not only create new view modes, but use special layouts for each view mode and content type. If you also have the Omega theme installed, Display Suite will give you some fluid, responsive layouts to choose from as well.

To be clear, Display Suite will create a layout *within* your page layout. It is specific to the view mode and that content type. I say this because styling might get muddy if you use it too much or inappropriately. That said, it's a great tool :)
> 2 votes

---
Tags: commerce
---


# Question
Title: How to display the title at the end of the breadcrumb?
I would like the page title to be displayed as a part of the breadcrumb, at the end of the preceding path.

I've got the following code.

```
<div id="breadcrumbs"><span class="bread_crumbs"><?php print $breadcrumb; ?><?php print $title; ?></span></div>

```

I have checked the following option in appearance/settings: Append a separator to the end of the breadcrumb.

If the page is a top level page, the breadcrumb displays correctly; however, for any further level pages, the title doesn't display, but just the previous path.

How do I change this to get it to work?

This is what I would like to do: Adding the page title next to the breadcrumb.

I've now got the following code.

```
<div id="breadcrumbs"><span class="bread_crumbs"><?php print $breadcrumb . $title; ?></span></div>

```

The page title only displays for top level pages. If a page has parents, then the title doesn't get displayed. I've cleared the cache, but still no luck.

# Answer
In template.php of your theme folder you can do this:

This is for changing the seperator or overriding the already available breadcrumb:

```
function mytheme_breadcrumb($variables) {
  $sep = ' > ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']) . $sep;
  }
  else {
    return t("Home");
  }
}

```

For adding title of page next to the breadcrumb you simply do this.

In page.tpl.php of your theme folder:

```
<div class="breadcrumb"><?php print $breadcrumb . $title; ?></div>

```

**\[Alternative Answer\]:**

If you dont want to do with custom code then you can try this module(Menu Breadcrumb) which will have option for adding page title at the end of breadcrumb.

In the configuration of this module you need to check this option for getting page title `use menu the page belongs to the breadcrumb`

Module Name is Menu Breadcrumb
> 1 votes

---
Tags: breadcrumbs
---


title: taxonomy CSV import in linux

text:
# Question
Title: taxonomy CSV import in linux
taxonomy CSV import How do use taxonomy CSV import the Chinese characters in linux ,Now I import all is empty Thank you for your help me to answer

# Answer
> 0 votes
you can use this module to import taxnonomy terms with any translations Taxonomy CSV import/export

---
Tags: taxonomy-terms
---


title: Open user login in lightbox

text:
# Question
Title: Open user login in lightbox
How to create a link, which will open user login in lightbox, I have installed lightbox2 module in Drupal 7.

# Answer
> 2 votes
Or try using Ajax Login/Register, a complete solution. Here is a quote about it (from the module's project page):

> ... provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.
>
> Features:
>
> * This module provides a block with 2 links (Login, Register) for the anonymous user.
> * When the user clicks on Login or register the requested form appears in a nice ajax popup.
> * The login and register forms can validate using ajax and not redirect on error.
> * On success the module redirects to the user page.
> * When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
> * This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.

# Answer
> 1 votes
You can add rel="lightmodal" to any anchor and it will be opened in a lightbox. Also I'm almost sure lightbox2 have this option (login lightbox) out of the box, check the settings form.

# Answer
> 0 votes
Try using: http://drupal.org/project/colorbox I believe it allows for this functionality out of the box. This post explains how to make a login link open in the colorbox; http://drupal.org/node/883210

# Answer
> 0 votes
Indeed, the AJAX Login/Register module adds a block with a login button. Clicking on that button opens a popup login/register dialog.

However, I think the question was how to make **any link** open the login dialog (e.g. I have blog posts, and clicking on the post title should also open the dialog.

This code does the trick however unlike the regular block dialog, it takes 5 seconds until the popup loads. Anyone knows why?

---
Tags: 7, users, javascript
---


title: Adding html/css to a module form

text:
# Question
Title: Adding html/css to a module form
How would I go about adding html/css into this module e.g. to place the different form items into a table, so i could have a column with one field entry the next column with another entry, and then rows below with other entry fields. I noticed when i put an image into the module it appears on every page on the website too?

```
 function form_example_menu(){
   $items = array();
   $items['form_example'] = array(
   'title' => 'My example form',
   'type' => MENU_NORMAL_ITEM,
   'access arguments' => array('access form_example'),
   'page callback' => 'drupal_get_form',
   'page arguments' => array ('form_example_form'),
     );
 return $items;
  }

function form_example_form($form, &$form_state){

    $form['mytextfield'] = array (
    '#type' => 'textfield',
    '#title' => t('My text field'),
    '#size' => 60,
    '#maxlength' =>128,
    '#required' => TRUE,
     );

 $form['mytext'] = array (
   '#type' => 'textarea',
   '#title' => t('My text area'),
   '#description' => t('enter some text.'),
   '#defauly value' => '',
   '#required' => TRUE,
  );

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

```

# Answer
> 1 votes
You can use `#prefix` and `#suffix` to add any amount of html markup to your form and/or any of its fields. Tons of information can be found in the Drupal Form API Reference. I would tend to suggest you stay away from tables and instead investigate css floats and divs, most probably doable without any additional markup, but that's just personal preference.

# Answer
> 0 votes
You can also theme form using hook\_theme and using theme function for its theme like:

```
function form_example_theme($existing, $type, $theme, $path) {
  return array(
      'form_example_form' => array(
          'render element' => 'form',
      ),
  );
}

function theme_form_example_form($variables) {
  $form = $variables['form'];
  $output = '';
  $output.= '<div class="custom-form">
              ' . drupal_render($form['mytextfield']) . '
             <!--  Add your HTML and render field the same way  -->
            </div>';
  $output.= drupal_render_children($form);
  return $output;
}

```

---
Tags: 7, forms
---


# Question
Title: Drupal 7: Filter nodes with a date range arround an exposed date
My issue is somewhat opposite of the common "List nodes within a date range".

So, I have an Event content type, with fields start\_date and end\_date. They show when the event starts, and when the event ends. Now I need to be able to select a date and fetch all events for which start\_date \< selected\_date and end\_date \> selected\_date.

The selected date should be an exposed filter to all users, or any other way that makes it possible to be fetcher from the URL.

Thanks in advance!

# Answer
> 7 votes
Have you tried adding an exposed filter in your view? I'm assuming you're using a view already, and I'm assuming you're using Drupal 7 (it's always helpful to specify that in the question, by the way :-)).

Add the date in question to your list of filters, check the box to expose it to users and use the 'is not between' option. Then you can either specify a hard coded date for the 'from' and 'to' or you can even use a relative date (second value type option) and specify something like '-30 minutes' and '+30 minutes' and it will re-calculate them based on the current time...

Hope this helps. Let us know if it works.

# Answer
> 1 votes
You may want to know that you can also use Views between dates filter module which was designed for this purpose.

You only need to install it and configure it and just select the two date fields and select its granullarity (in my opinion this is a problem since if you select year, month and date it wouldn't work if you typed only a year.

---
Tags: views, 7, nodes
---


# Question
Title: How to implement User registration settings email in my registration form
I have a `custom registration` field that i have in my `drupal 6` site.Once a user has been `registered` a `mail` will be send to the corresponding user with his or her `account credentials`.I have used `drupal_mail function` for this purpose.Is there any means by which i could create such a mail through the back-end. I have seen `User e-mail settings`.Is it possible to implement this `mail function` through the `back-end` rather than programatically. Is yes i would be really curious to look up on that.Hope someone might help me with this..

# Answer
> 1 votes
You could use the Rules Module for this.

**Steps**:

1. Define an Event that whenever a registration is there.
2. Then Define the Action to send Mail with proper Format.

For more details about the Rules module go through README.txt of this module.

# Answer
> 1 votes
i think you are expecting a place where you can create a email template and then call or use the same template using Rules or code depending on action.

if you want to maintain only less templates then Rules module is the more than sufficient.

or, you have many templates, then PET is the solution, where you can create N number of templates, those templates can be triggered manually or using Rules.

# Answer
> 0 votes
Instead of using the Contributed Module you could also go for writing a custom Module ie defining hook\_mail() when a particular event go for.

```
function hook_mail($key, &$message, $params) {
  $account = $params['account'];
  $context = $params['context'];
  $variables = array(
  '%site_name' => variable_get('site_name', 'Drupal'),
  '%username' => format_username($account),
);
if ($context['hook'] == 'taxonomy') {
  $entity = $params['entity'];
  $vocabulary = taxonomy_vocabulary_load($entity->vid);
  $variables += array(
  '%term_name' => $entity->name,
  '%term_description' => $entity->description,
  '%term_id' => $entity->tid,
  '%vocabulary_name' => $vocabulary->name,
  '%vocabulary_description' => $vocabulary->description,
  '%vocabulary_id' => $vocabulary->vid,
 );
}

// Node-based variable translation is only available if we have a node.
if (isset($params['node'])) {
  $node = $params['node'];
  $variables += array(
  '%uid' => $node->uid,
  '%node_url' => url('node/' . $node->nid, array('absolute' => TRUE)),
  '%node_type' => node_type_get_name($node),
  '%title' => $node->title,
  '%teaser' => $node->teaser,
  '%body' => $node->body,
 );
}
$subject = strtr($context['subject'], $variables);
$body = strtr($context['message'], $variables);
$message['subject'] .= str_replace(array("\r", "\n"), '', $subject);
$message['body'][] = drupal_html_to_text($body);
}

```

For More details go through the link.

---
Tags: 6, emails
---


# Question
Title: How to alter account activation mail Depending on roles
In account settings ,Account Activation mail settings is general i think so.

I want the account activation mail to be altered. I want to check roles, according to that display the mail messages .

how will i do that?

# Answer
> 2 votes
You can create a new rule like this

`EVENT` saying `After saving a new user account`

```
Conditions saying  User has role(s)  check your role there.

```

`Actions` saying `send mail` you can send the mail what you want in that.

# Answer
> 2 votes
You should look into the hook\_mail\_alter for overriding the mail, which get send after user\_save. You can look into the answer given for this question here --

Override \_user\_mail\_notify() to NOT send email on user\_save() if user status is changed

Though question is not relevant but the answer is.

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


title: ahah helper populate dependent dropdown

text:
# Question
Title: ahah helper populate dependent dropdown
I am using the ahah helper as I couldn't seem to get my dropdown lists to depend on each other anyother way in Drupal 6. Below is my code, I can hard code the changes so that the second dropdown populates with the correct values. However when I select a value from dropdown one `An error occurred.
/drupal1/?q=ahah_helper/dependent_select
(no information available).`

There is no error in my httpd log. All i have changed is, added a DB connection, two queries to populate $grouplist and $sitelist with the latter referencing the selected value from list one for the WHERE clause in the query. I am still passing a ID number which refers to a value. See directly below for the previous code that worked in the example. I have taken the $select1\_selected and used that within the query that populates dropdown2.

Dropdown one options = `'#options' => array( 1=> 'USA', 2 => 'German'),`

Dropdown two options =

```
 if ( $select1_selected == 1 ) {
    $select2_options['11'] = 'GM';
    $select2_options['12'] = 'Ford';
} else if ( $select1_selected == 2 ) {
    $select2_options['21'] = 'VW';
    $select2_options['22'] = 'Audi';
}

```

**My Code:**

```
    function ahahdrop_menu(){
        $items = array();
        $items['ahahdrop'] = array(
        'title' => 'Ahah Drop menu',
        'type' => MENU_NORMAL_ITEM,
        'access arguments' => array('access ahahdrop'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array ('ahahdrop_form'),
    );
return $items;
 }

    function ahahdrop_form( $form_state ) {
        $form = array();
    // this is standard method for register ahah helper for current form
        ahah_helper_register($form, $form_state);

    // we are building fieldset
        $form['dependent_select'] =
        array(
         '#type'   => 'fieldset',
         '#title'  => t('Dependent Select '),
         '#prefix' => '<div id="dependent-select-wrapper">',  // specify wrapper element id
         '#suffix' => '</div>',
         '#tree'   => TRUE,  // this should be TRUE
         );

    // provide default option for select one
        $select1_selected = 11;

    // $form_state['storage'], contains ahah submitted values
        if ( isset($form_state['storage']['dependent_select']['select1']) ) {
    // get 'select1' selected option
        $select1_selected =  $form_state['storage']['dependent_select']['select1'] ;
}

 try {  $conn = new PDO("pgsql:host=localhost port=5432 dbname=riverflies_gis", "opengeo", "opengeo");
        echo "Connected";
            echo "<br>";
    }
        catch(PDOException $e) {
            echo $e->getMessage();
        }

        $stmt2 = $conn->prepare("SELECT group_id, rmigroupname FROM rmi_group_tbl ");
            if ($stmt2->execute()) {
                $stmt2->setFetchMode(PDO::FETCH_OBJ);
                    $grouplist = array();
                        foreach ($stmt2 as $row) {
                        $grouplist[$row->group_id] = $row->rmigroupname;
            }
    }

        $stmt3 = $conn->prepare("SELECT site_id, sitename, group_id FROM sites_tbl WHERE group_id = $select1_selected ");
            if ($stmt3->execute()) {
                $stmt3->setFetchMode(PDO::FETCH_OBJ);
                    $siteslist = array();
                        foreach ($stmt3 as $row) {
                        $siteslist[$row->site_id] = $row->sitename;
            }
    }

    $form['dependent_select']['select1'] =
        array(
         '#type'    => 'select',
         '#title'   => t('Select 1'),
         '#options' => $grouplist,
         '#default_value' => array( $select1_selected ),
         // specify ahah event
         '#ahah' => array(
                        'event'   => 'change',  //  this is onchange event of select
                        'path'    => ahah_helper_path(array('dependent_select')),
                        // provide temporary path
                        // no need to register it through hook_menu
                        'wrapper' => 'dependent-select-wrapper',
                        // provide the wrapper of element
                        // here we have given the id of fieldset
                        ),
          );

    $form['dependent_select']['select2'] =
        array(
         '#type'    => 'select',
         '#title'   => t('Select 2'),
         '#options' =>  $siteslist // set dynamic options
         );

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

    return $form;
    }

```

# Answer
See the ahah drop down examples in drupal examples module
> -1 votes

---
Tags: forms, database, ajax
---


# Question
Title: How would i redirect a user after registration to his subdomain site
I want to redirect a user after successful registration `maindomain.com` to open his site in a `new tab`.

His site `url` will look like this `newuser.maindomain.com`. (username.maindomain)

Any Suggestions?

# Answer
> 3 votes
Use Rules again to do the redirect.

On Event **Drupal is initializing** or **User has logged in** add a condition if you need that (eg **check that user role is not anoymous**) and then add an Action of **Redirect**. In there use some php for the redirect path using the global variable $user (you may need some formation also if the username has spaces).

Notice that you must **run this Rule after the rule that creates the subdomain**. Or you can simply add the redirect action on the same domain\_rules rule after the component that creates the subdomain.

You must also have a common user database along sites (domain and subdomain). The Bakery module is a good option here.

# Answer
> 0 votes
i feel you have to use SSO for authentication among multiple domains, check this bakery module!

---
Tags: 7, users, subsites
---


title: Please Help Fixing this Simple Module

text:
# Question
Title: Please Help Fixing this Simple Module
I have the following code that set a button to download a file using display suite code field:

```
<?php
global $user;

if (!isset($_SESSION['downinc'])) $_SESSION['downinc'] = 1;

if ($user->uid) $_SESSION['downinc'] = 0;
?>

<form id="form1" name="form1" method="post" action="/downloadcode">
    <input type="hidden" name="download_code" id="download_code" value="[node:field_code_file]" />
    <input type="hidden" name="uri" id="uri" value="[node:url:relative]" />
    <input type="submit" class="downloadButton" value="Download Code">
</form>

```

When the Download Code button is clicked, it will call the module that I have created as follows:

```
<?php
function custom_download_menu() {
    $items['downloadcode'] = array(
      'page callback' => 'custom_download_view',
      'access arguments' => array('access content'),
      'access callback' => TRUE,
    );
    return $items;
  }

function custom_download_view() {
    $js = "var time_left = 5;
        var cinterval;

        function time_dec(){
        time_left--;
        document.getElementById('countdown').innerHTML = time_left;
        if(time_left == 0){
            clearInterval(cinterval);
        }
    }

    cinterval = setInterval('time_dec()', 1000);";
    drupal_add_js($js, 'inline');

    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache"); // HTTP/1.0
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

    $tracker = array(
        'database' => 'c1tracker',
        'username' => 'c1tracker',
        'password' => 'mypass',
        'host' => 'localhost',
        'driver' => 'mysql',
    );

    Database::addConnectionInfo('tracker', 'default', $tracker);
    db_set_active('tracker');

    $current_ip = $_SERVER['REMOTE_ADDR'];
    $referrer = $_SERVER['HTTP_REFERER'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    global $user;

    if (!isset($_SESSION['downinc'])) {
        //set session here since it was not set from the referrer page because of caching.
        $_SESSION['downinc'] = 1;

        $error = "Invalid download. No Session.";

        $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

        db_query($sql);
    }

    if (!isset($_POST['download_code'])){
        $error = "Invalid download. File not set.";

        echo "<p>$error</p><p>Please clear your browser's cache.</p><h4><a href=\"http://www.mysite.com/user/register\">Sign up</a> now or <a href=\"http://www.mysite.com/user/login\">login</a> if you are an existing member.</h4>";

        $sql = "INSERT INTO `download_log` (`id`, `error`, `ip_address`, `referrer`, `user_agent`, `date_time`) VALUES (NULL, '$error', '$current_ip', '$referrer', '$user_agent', now())";

        db_query($sql);
    }else{
        $file = $_POST['download_code'];

        if ( $_SESSION['downinc'] < 4 || $user->uid ) {
            header("Refresh: 5; URL=$file");

            $_SESSION['downinc'] = $_SESSION['downinc'] + 1;

            echo "<p>Your download will start in <span id=\"countdown\">5</span> seconds...</p>";
        }else{
            $uri = substr($_POST['uri'],1);

            echo "<p>You have downloaded code 3 times.</p><p>To continue downloading, please login or register.</p><h3><a href=\"http://www.mysite.com/user/register?destination=$uri\">Sign up</a> now or <a href=\"http://www.mysite.com/user/login?destination=$uri\">login</a> if you are an existing member.</h3>";
        }
    }

    db_set_active();

    echo "<p>Problems with the download? Please go back to previous <a href=\"$referrer\">page.</a></p><p>If you have problem downloading this file, kindly <a href=\"http://www.mysite.com/contact\">contact us</a>.</p>";
}

```

I know that this is not a perfect module and needs to be rewrite. Since I am new to creating a module in Drupal 7, I am trying hard to fix this and make it standard.

Currently I can download the file without problem. What is missing here is when it redirects to www.mysite.com/downloadcode, the only content I see is this:

```
Your download will start in 5 seconds...

Problems with the download? Please go back to previous page.

If you have problem downloading this file, kindly contact us.

```

The template is gone totally. No header, sidebar, footer, no themes at all. And also the countdown javascript did not work. Anyone know how to fix this?

# Answer
> 2 votes
The reason why you don't get anything you normally see in a Drupal page is that you are printing the output, which is what you would do (for example) when the menu callback needs to only return a XML string, without anything else. (Think of the XML sitemap module when it returns the XML sitemap of the site.)
When you need to see the output of the menu callback put in a Drupal page, the menu callback needs to return:

* A string, which can contain HTML tags
* An array as accepted by drupal\_render()

The reason of this is evident in the code of drupal\_deliver\_html\_page().

```
  // Menu status constants are integers; page content is a string or array.
  if (is_int($page_callback_result)) {
    // …
  elseif (isset($page_callback_result)) {
    // Print anything besides a menu constant, assuming it's not NULL or
    // undefined.
    print drupal_render_page($page_callback_result);
  }

  // Perform end-of-request tasks.
  drupal_page_footer();

```

If your menu callback doesn't return anything, neither branches of the control statement will be executed, and Drupal will not call drupal\_render\_page(), which is the function that renders a page.

As for what other is wrong in your code:

* drupal\_add\_http\_header() should be used instead of `header()`.
* The function to insert a new row in a database is db\_insert(), while db\_update() is used to update an existing row.
* A Drupal module should never access `$_POST`.
* If you set the access callback to `TRUE`, the access arguments are not used.
* Most importantly, you should not create a form without using the form API. If the code is trying to let the users upload a file, image\_example\_style\_form(), image\_example\_style\_form\_validate(), and image\_example\_style\_form\_submit() are perfect example of how to handle a file upload with the form API, although the code is for uploading an image.

```
// Use the #managed_file FAPI element to upload an image file.
$form['image_example_image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
  '#default_value' => variable_get('image_example_image_fid', ''),
  '#upload_location' => 'public://image_example_images/',
);

```

If the purpose of the code is letting users download a file, that can still be done with a form API form, since hidden is a form API's element. Send a CSV file to the user on FAPI form submit explains how to allow users to download a file with code inside a form submission handler.
Notice that you can always use drupal\_get\_form() to render a form from PHP code, supposing that Drupal has been bootstrapped, which is what happens when a module requires you to enter code that is passed to php\_eval().

---
Tags: forms, hooks
---


# Question
Title: Panel Content not displaying correctly after migrating site to new server
This is how it looks like after I migrated the site. I compared the new panelizer and panels folders with a backup folder that I had to see if there were discrepancies, but the folders had the same files. I also resaved the admin page as suggested in another post, but that didn't do it for me.

I am using D7 by the way.

# Answer
When you're browser builds the admin page, it makes multiple requests over HTTP to the server to fetch resources, such as css files. If you look over that list, using whatever debugging tools your browser provides, you might be able to find out which file Panels is expecting to be there, but your browser fails to find.
> 1 votes

---
Tags: panels, theming, migrations
---


# Question
Title: Views node author relationships with profile2 owner
I have a multi user site, with Profile2 enabled. And I've set up a views block which is only displayed on the Profile2 page, and is *supposed* to list content/nodes authored by the Profile2 page owner.

Now I've made a similar block for the user-page, which works perfectly, using the Content:Author relationship and a Content:Author UID(providing ID from URL as the default value) contextual filer.

But I just can't figure out which relationship(s) and contextual filter to use for the Profile2 page. Now I'm completely lost and googly eyed from trying random combinations.

Am I doing something wrong, or is it just not possible to filter the Author ID from the Profile ID(i.e does https://drupal.org/node/1834920 have something to do with my issue?)? Any hints or suggestions would be greatly appreciated!

Cheers,

Matt

# Answer
> 1 votes
I managed to get around this by setting up relationships with Content:Author and (author)User:Profiles. Then setting up a Contextual Filter of Content:Author UID, with Raw Data from URL, using Path Component 2, as the Default Value.

---
Tags: views, users
---


# Question
Title: Open the AJAX Login/Register popup when clicking on post titles
The AJAX Login/Register module adds a block with a login button. Clicking on that button opens a nice popup login/register dialog.

But how to make the login dialog open when clicking on post titles?

I tried to add a block with this code:

```
<a href='ajax_register/login/nojs'
   classes='ctools-use-modal ctools-modal-ctools-ajax-register-style'
   rel='nofollow'>
     My Post Title
</a>

```

However it doesn't work. Anyone knows why?

# Answer
You simply have a typographic error. Use "`class=...`" instead of "`classes=...`"
> 1 votes

---
Tags: ajax, users, javascript
---


title: Form Set Error in custom module

text:
# Question
Title: Form Set Error in custom module
I am using Drupal7. I also use ife module. I also wrote a custom module

Here is my code

```
function mymodule_validate($form, &$form_state) {
    $name=$form_state['input']['name'];
    $pass=$form_state['input']['pass'];
    if(empty($pass) || $pass=='') {
           form_set_error('name', t('dummy message'));
        $errors=form_get_errors();
        print_r($errors);
        return $form;
    }

```

I also did some RND. when I check $form\_state under complete form I got this array

```
 [complete form] => Array
        (
            [#action] => /logintest/node?destination=node
            [#id] => user-login-form
            [#validate] => Array
                (
                    [0] => user_login_name_validate
                    [1] => user_login_authenticate_validate
                    [2] => user_login_final_validate
                    [3] => mymodule_validate
                    [4] => ife_form_validator
                )

```

Here means the sequence of module working functions.

Now when I print $errors, it is showing

```
Array
(
    [pass] => Password field is required.
    [name] => Sorry, unrecognized username or password. <a href="/logintest/user/password">Have you forgotten your password?</a>
)

```

But I am accepting

```
Array
(
    [pass] => Password field is required.
    [name] => dummy message
)

```

But I don't know why it is not overwriting custom message.. Can anybody tell me how to resolve this issue.

Thanks a lot.

# Answer
You can try this under your hook\_validate

Here i added new function name mymodule\_soft\_block\_validate

```
 function mymodule_validators() {
        return array('user_login_name_validate', 'user_login_authenticate_validate', 'mymodule_soft_block_validate','user_login_final_validate','mymodule_validate');
    }

function  mymodule_soft_block_validate($form, &$form_state) {
        $pass=$form_state['values']['pass'];
        if(empty($pass) || $pass=='') {
            form_set_error('name', t('dummy message'));
            return $form;
        }

}

```
> 5 votes

# Answer
I think you should use

```
$name=$form_state['values']['name'];
$pass=$form_state['values']['pass'];

```

Instead of:

```
$name=$form_state['input']['name'];
$pass=$form_state['input']['pass'];

```

For the rest, I am not sure exactly what is the error. Can you clarify a little bit the use case. Regards !
> 0 votes

# Answer
You can try this one for setting the error message.

```
function hook_validate($form, &$form_state) {
  if (strlen($form_state['values']['name'])==0) {
    form_set_error('name', t('word not long enough'));
  }
}

```
> 0 votes

# Answer
```
[#validate] => Array
                (
                    [0] => user_login_name_validate
                    [1] => user_login_authenticate_validate
                    [2] => user_login_final_validate
                    [3] => mymodule_validate
                    [4] => ife_form_validator
                )

```

As I can see from your RND that **ife\_form\_validator** is overriding your messages. For this purpose, you will have to increase the weight of module.

**Drupal 7:**

```
/**
 * Implements hook_enable()
 */
function MODULE_NAME_enable() {
    db_update('system')
    ->fields(array('weight' => 100))
    ->condition('type', 'module')
    ->condition('name', 'MODULE_NAME')
    ->execute();
}

```

**Drupal 6:**

```
/**
 * Implementation of hook_install()
 */
function MODULE_NAME_install() {
  drupal_install_schema('devel');

  // New module weights in core: put devel as the very last in the chain.
  db_query("UPDATE {system} SET weight = 100 WHERE name = 'MODULE_NAME'");

  ...
}

```

I would suggest that you verify the weight of **ife\_form\_validator** module first. Then, increase the weight of the module in which you are using the following code:

```
function mymodule_validate($form, &$form_state) {
  $name=$form_state['input']['name'];
  $pass=$form_state['input']['pass'];
  if(empty($pass) || $pass=='') {
    form_set_error('name', t('dummy message'));
    $errors=form_get_errors();
    print_r($errors);
    return $form;
}

```
> 0 votes

---
Tags: 7
---


# Question
Title: Users and Forum Transfer from a live site to a staging site
How do I transfer just the Forum of a Drupal site to another Drupal site as my staging site is lagging behind the live site, So I need to update it with the live site forum content and then publish my staging site as the live site afterwards.

# Answer
Use Features for all need of these kind. Module page explains -

> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

So you can make feature of your users setting as well as forum and you can always track the changes at your staging site and if it's overridden then you can make it again and apply the changes at live site by replacing the created feature and enabling it..
> 0 votes

---
Tags: migrations
---


# Question
Title: allow only the author of the comment node
I want to make an option to subscribe to news within the node, node - it's maintenance team that adds news. I decided to do with the comments as flag in this case does not fit. Everything seemed to be fine, I can add the required fields in the form of comments and install the Node notify that and give the ability to subscribe to a node. But then the question I give the ability to add comments to the author node and not the whole role, and I need to limit the addition of the comment and make only the author can add nodes. anonymous and everyone else can only view and subscribe. Sorry for my English. Thanks for any help!

# Answer
I decided to create a question of custom module with the given code:

```
function comment_author_form_comment_form_alter(&$form, &$form_state, &$form_id){
//dsm($form);
 global $user;
 //dsm($user);
   if ($form['#node']->uid != $user->uid && $user->uid != 1) {
    // Form alter here to unset comment form
    $form['#access'] = FALSE;
    }
  }

```
> 0 votes

# Answer
In the `permissions` of `Comment` you can allow `Post comments` for your author role alone.For `anonymous user` you can give permission of `view comment` alone. Hope this helps you :)
> 1 votes

---
Tags: comments
---


title: Node Access Product + UC Marketplace

text:
# Question
Title: Node Access Product + UC Marketplace
I want store owners to be able to offer node access to people who purchase their products.

The only problem with this, is when I give the permission "Create and edit NAP" to the developer/store owner role, it gives the permission to ALL nodes.

I've looked for a setting to change this, so that it is only for nodes who have the same author as the current logged in user, and I'm not seeing a way to do this anywhere.

What am I doing wrong? Is there a different module to accomplish this? Should I custom code something?

# Answer
> 0 votes
I had to restrict this by modifying the module and adding a setting.

# Answer
> 0 votes
Can you give more detail on the problem and your setup. For example what is a store owner, is this just and administrator of a single site or do you have many store owners on one installation, for example some kind of marketplace?

What do you mean by node access? you want customers to buy a product and then be able to view or edit it.

What version of ubercart/drupal are you using?

If the scenario is you have only one store owner per site and you want a customer to purchase a product and then have view access to a specific node I would look into using the following modules

* node reference / entity reference - create a reference to a node from a product
* content access - this allows fine grained permissions for individual nodes or for content types etc
* Rules - create a rule that after successful checkout grants permission to the node that is referenced on the product

# Answer
> 0 votes
You just need to configure the Content Access Module:

1. Download Content Access: https://drupal.org/project/Content\_Access
2. Enable it
3. Edit your node content type and go to "Access Control"
4. Uncheck the user role for "View any \[content\_type\_name\]" and below that check the user role for "View own \[content\_type\_name\]" only.

And you're done.

---
Tags: ubercart, users
---


# Question
Title: Webform AJAX submission, same problem with multiple approaches
I'm trying to set up a Webform with AJAX submission. I've tried 3 approaches in order to complete it, all 3 resulted in the same problem.

I've tried the Webform AJAX module, I've tried a code from this answer and I've tried another module that is in sandbox only in Drupal.org but it supposed work just fine.

Some of these approaches worked on other Drupal projects on mine but not on the current one.

After clicking on the Submit button, the little AJAX loading gif shows up and then the gif remains there but the submission never finishes, the form doesn't get submitted. Exactly the same problem for all approaches.

This is a JS error I'm getting in console

```
Uncaught TypeError: Object function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } has no method 'handleError' jquery.form.js?v=2.52:12
s jquery.form.js?v=2.52:12
window.(anonymous function) jquery.form.js?v=2.52:12
onload

```

Do you have any idea what could possibly cause a bug like this in Drupal 7 with AJAX webform submission?

# Answer
> 0 votes
I've solved the problem with using jquery.form plugin and submit the form via AJAX with the help of this plugin.

I've found this solution in this answer

https://drupal.stackexchange.com/a/23650/9297

---
Tags: 7, webforms
---


# Question
Title: How can I include ratings in the site, with reference stored in the node table?
I need to implement ratings for my site. I have already stored the data in the node; now, I need to store the average ratings point in the node field type which I have created. It must be the reference for the ratings table.

How can I implement this?

# Answer
You can use Fivestar module for this.

> The Fivestar voting module adds a clean, attractive voting widget to nodes in Drupal 5, node and comments in Drupal 6, and any entity in Drupal 7.

You configure which content type should have the Fivestar module enabled; you can also set the permissions for the users who can vote etc. You will have multiple option to show the vote result on the configuration page of module.

I have used it in 3-4 e-commerce websites and it works simply great.
> 1 votes

---
Tags: entities, nodes, rating
---


# Question
Title: Can I create a node, assign a language and provide it a menu link with Drush?
Just that. Can I create a node, assign a language and provide it a menu link with Drush?

Let say, I want to create a node:

* of the **basic** content type
* with **title** set to "my title"
* set to **es** language
* and provide it a menu link in the **Main menu**

# Answer
> 1 votes
Not out of the box. See this prior related question, all of these examples are created through the Devel 'generate content' library but they assume generic (ex. lipsum) content. For a custom build like you are asking with a specific title, you're best bet is going to be to create a custom Drush plugin using node\_save to programmatically create a node with the values you want.

---
Tags: drush
---


title: drupal_add_js only once

text:
# Question
Title: drupal_add_js only once
I have a field which is used in a nodeblock, and only appears on a few select pages. This however will vary throughout the lifetime of the website so I've been looking for a way to insert the Javascript this field requires only when it's present. Additionally, the field can appear more than once on any given page.

Looking at `drupal_add_js`, I can't see that it provides a way to only include JS once. Using this I was hoping that I could just call it in the `field--field-name.tpl.php` file for that field but as it occurs multiple times, the JS is included more than once.

I've looked at the module JS Injector, but that's just page specific and just calls the aforementioned function. This wouldn't help me because every time a new block is added somewhere, the list of pages including the JS would also need to be updated.

Is there a way I can include a JS file just once in Drupal?

# Answer
It depends what type of javascript you are adding.

* drupal\_add\_js will only add *files* once, no matter how often it's called ;
* *Settings* would overwrite previous values, so it's not a major problem ;
* *Inline code* would indeed get added multiple times.

Given that your script needs including only once no matter how often the field is present, I assume you are not generating it's code on the fly - so putting it in a file would be an option.

Otherwise, as suggested by Clive, you could have your own wrapper around drupal\_add\_js that ensures a given inline js is only added once by using a static variable.
> 6 votes

---
Tags: 7, javascript
---


# Question
Title: Why is it sometimes $node->field_name[0], and sometimes $node->field_name['und'][0]?
Sorry for the code in the title, I couldn't think of a clearer way to ask it.

I have several nodes of the `location` content type, and a view outputting teasers of those nodes. I want to do some custom stuff in `node--location.tpl.php` to affect the teasers everywhere they're displayed. When I do a simple `dpm($node)` to get at the variables, some field values are not always in the same place.

For instance, I have `field_phone` that just has identically formatted phone numbers. For the first node in this view, that field is structured as `$node->field_phone['und'][0]['safe_value']`. But for the second node, it's simply `$node->field_phone[0]['safe_value']`.

I know that `und` has to do with translations, and perhaps means "undefined". I'm not doing *anything* with translations or localization or languages on the site, so it's not like this node is any different from other nodes that way.

What causes this, and is there a function or something that can help me test for and get at the value easily, or do I have to roll my own?

**EDIT**: Chris Rockwell below points out `field_get_items()`. This seemed to solve my problem on the site I was working on the other day. But now, on a different site, it's failing for exactly the reason I bring up here.

I have a view that outputs three nodes. For some reason, when I `dpm($node)` in the `node--node-type.tpl.php` file, I get *six* variable dumps. The *first* one has `$node->field_link_image['und'][0]`, while all five others — **INCLUDING** the duplicate of this same node — just has `$node->field_link_image[0]`. And now, `field_get_items()` is silently failing and returning false on those last five nodes.

So I go back to my original question: What causes this difference between some node variables and others, and what can I do about it?

# Answer
The lack of the `'und'`, or `LANGUAGE_NONE` level data seems to indicate that the field has lost the ability to be translated. I've never encountered such a field.

`field_get_items()` as already pointed out is the canonical way to safely retrieve field data. Any fields that don't work with field\_get\_items should be considered broken.

I would hazard a guess that you either

1. Have a broken contrib module that re-arranges field data and doesn't know better than to sometimes remove the language level.
2. Your field settings have just broken somewhere along the way. Potentially because of a reason similar to above.

Does the problem keep happening on newly created fields?

Can you reproduce on a clean install?
> 8 votes

# Answer
I believe you need a combination of `field_get_items()` and `field_view_value()`.

In your case (I can't test this):

```
$item = field_get_items('node', $node, 'field_phone'); // unsafe to print
$output = field_view_value('node', $node, 'field_phone', $item[0]);
print $output;

```

EDIT: In the above code, line 2 (`$output = ...`), I added in `$item[0]` because I failed to see that `$item` requires a delta. This allows for fields which have multiple values to be iterated over and passed through `field_view_value()`. I believe you are skipping the important step of using `field_view_value()`.

If using the above code (including `field_view_value()`) doesn't solve this, I would need more information; e.g. seeing your node.tpl.php and possibly a content type export.
> 3 votes

# Answer
Here's the function I'm using until I find a better answer. In addition to fixing the language issue, it should also always return a numeric array, so you can be confident in `foreach`ing over the result.

```
function get_field($field, $lang = 'en', $fallback = 'en') {
    $var = FALSE;
    if(!empty($field[$lang])) {
        $var = $field[$lang];
    } elseif(!empty($field[$fallback])) {
        $var = $field[$fallback];
    } elseif(!empty($field['und'])) {
        $var = $field['und'];
    } elseif(!empty($field)) {
        $var = $field;
    }

    if(empty($var)) {
        return false;
    }

    if(!empty($var[0])) {
        return $var;
    } else {
        return array($var);
    }
}

```
> 0 votes

# Answer
If you take a look at this https://api.drupal.org/api/drupal/includes%21bootstrap.inc/constant/LANGUAGE\_NONE/7

this is a safer value to use and will work for any defined language, including no language.
> -3 votes

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


# Question
Title: Changing a menu's target nodes for each page
For a Drupal 7 website, I need to have 2 types of menus: 1 menu with a list of countries, each menu entry pointing to a given node. For each country page, I need to display a 'characteristics' menu, with fixed items (e.g. population, incomes), but (of course) the targeted nodes have to be changed in function of the current country. (Clicking on the 'characteristics' menu entries opens a page which is different for each country.)

Is there a module for that in Drupal 7, or a way to do that programmatically?

# Answer
I found an answer to my question: the best is to use a programmatic approach by using the `l()` function that is available anywhere within a Drupal installation. It accepts three arguments:

* $text: The text that will be visible to users for your link
* $path: The URL that the link will go to when clicked.
* $options: An associative array which allows to set additional parameters to further customize the link with CSS classes etc…

A good introduction is found here: http://www.pixelclever.com/how-and-why-use-l-function-create-links-drupal-programming. This function can be used in the template files, or directly from a node body.
> 0 votes

---
Tags: 7, routes
---


title: Drupal 7 IMCE image paths

text:
# Question
Title: Drupal 7 IMCE image paths
I develop sites on my server then move them when ready. I just started using IMCE and everything works well other than the image path. For instance:

The path shows */test/sites/default/files/images/test.png* however I want */sites/default/files/images/test.png* so when I move the site I don't have to redo all the images.

I set the rewrite in the `.hataccess` file and I set the base url in `settings.php`. Is there something else I need to set?

# Answer
> 2 votes
If you develop your site in a sub folder, rather than a subdomain, you are going to be in for a bad time. All of your image paths and links are going to be incorrect. You are better of moving to a subdomain instead. If its already too late then use the Pathologic module to clean them up.

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.

---
Tags: 7, files
---


# Question
Title: Can I simply delete the File Entity folder from Modules if I am using Media 7.x-1.3
When I try to create new content with a linked YouTube video I am getting the following error:

> Fatal error: Call to undefined function file\_info\_file\_types() in /home/setstart/public\_html/sites/all/modules/media/media.module on line 1084

I have inherited a site that use Media 7.x-1.3

I see that the following Module is also installed - File Entity 7.x-2.0-unstable7

I see from the following threads that the file entity submodule within Media should be used not the standalone one.

http://drupal.org/node/1516804

http://drupal.org/node/1850324

So it looks like File Entity 7.x-2.0-unstable7 should never have been installed.

Can I simply remove the independent File entity module? I see a lot of other modules state they depend on it (so I can't disable it from admin screen)

If not what is my best option? Upgrade to Media 2.x?

# Answer
> 2 votes
Do you have backups from before the 2.x version of File entity was installed? That would be the ideal solution because frankly, things are bad. You can't just remove the File entity 2.x module directory, because at this point the module has been installed and your data is at quite a dirty state. The only real solution is to try an in-UI disable/uninstall of File entity and any Media related modules to try and get your site to a more clean state before again installing and enabling the proper versions you need/want.

---
Tags: media, files
---


# Question
Title: Dynamic parameters passed to page callback
I have the following hook\_menu:

```
  $items['products/autocomplete.json/%'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products')
  );

```

Here is the function:

```
function json_list_products($keywords) {

  $items = array();
  foreach(_sql_select_products($keywords) as $product) {
    $items[$product['Product_ID']] = $product['Product_Name'];
  }

  drupal_json_output($items);
}

```

$keywords is not populated with the value of the % as i suspected - how do I populate this value?

Alex

# Answer
```
$items['products/autocomplete.json/%'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products'),
    'page arguments' => array(2),
  );

```

view the documentation at this link
> 2 votes

# Answer
Try this to start:

```
function mymodule_menu() {
  $items['products/autocomplete.json/%'] = array(
    'page callback' => 'json_list_products',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function json_list_products($keywords) {
  drupal_json_output($keywords);
}

```

Note the following:

* Set **page arguments** to position in your path where you expect the arguments in your callback to be. In your case, it's 2;
* I've set **access arguments** to be *access content* which is likely to be enabled for anyone. If this works, then check if you have a *access products* permission when testing;
* Remember to clear your cache after modifications. If you use drush, you can use `drush cc menu` from the command line;
* Use `MENU_CALLBACK` because otherwise Drupal will add a menu item to the Navigation menu, since the default is `MENU_NORMAL_ITEM`.

I've tested this and http://example.org/products/autocomplete.json/cook returns:

```
"cook"

```
> 2 votes

---
Tags: 7, routes, ajax
---


# Question
Title: Get value of a field attached to a user entity based on currently logged in user
I add a taxonomy selection to the registration from *config/account* called `field_user_class`.

Now for my module I need a function that returns the this field value for the currently logged in user, and shows it to them.

I just need the function to return this field for the logged in user.

# Answer
> 1 votes
```
global $user;
// Only if logged in
if($user->uid) {
  $logged_in_user = user_load($user->uid);
  $field_user_class = field_get_items('user', $logged_in_user, 'field_user_class');
  // Do stuff with array $field_user_class
}

```

# Answer
> 1 votes
There isn't a function that returns the value of a field for a user account, but you can use the following code.

```
$account = user_uid_optional_load();
$items = field_get_items('user', $account, 'field_user_class');

```

If you need to just display the entity field, then you should use the following code.

```
$account = user_uid_optional_load();
$items = field_view_field('user', $account, 'field_user_class');

```

In the latter case, keep in mind the notes shown in the documentation for field\_view\_field():

Bear in mind that you cannot use the global `$user` variable, since that doesn't contain a full-loaded user object. That is why you need to use a function that loads the user object from the database, which is what user\_uid\_optional\_load() does.

---
Tags: users
---


# Question
Title: Creating view using a field(checkbox) as Contextual Filter
I have a content type `product`.I want to create a page view of the products. The view should show only those products whose field `featured` (checkbox) is checked.

How do I use Contextual Filters for this ?

If the field was a taxonomy-term ,I would go to `Provide default value -> Taxonomy Term ID from URL.`

But, since the field is a checkbox I am not able to achieve this.

Thank you .

# Answer
If you want this filter you should add the field as a "standard filter" and not contextual filter. In Views UI look for the headline Filter criteria, add your field "featured" and choose what value that has to be set.

Here is a screenshot how the UI looks, it is under filter criteria where you should push add.
> 1 votes

# Answer
I went through to the same issue. The problem, is that when you add a "checkbox" field in your content type, by default, the values of your checkbox are empty.

In order to be able to use the featured field (checkbox) as a filter in your view, you have first to define the 2 possible values of your checkbox when editing your feature field of the content type. You can put any pair of values you want, yes/no, 1/0, true/false, pretty/ugly...etc

Find attached below 2 images as examples.

Hope it will help.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Is it possible (and within convention) to insert a hidden field in an views exposed filter to control form content (e.g for re-submit search)?
Examples:

1. (my requirement) when wanting to control the content of the view title for a listing of locations (E.g. title "venues near you") created using a view with Drupal module ip\_geoloc ("IP Geolocation Views & Maps") based on the user's detected location (via html5 geo location) and then offering further searches (e.g. a different specific location) and wanting to display a different title in those results "venues near New York City"
2. simpler example "search again" for subsequent displays of the form (an user-visible views exposed filter).

For example 1., I'm currently using `hook_views_pre_render` in my own custom module to compare the submitted value with the detected location to be able to set a custom title for the view, *snippets* (note, not full declaration and module) of how I get each of these here:

```
    $locationAsString = "";

    if (function_exists('ip_geoloc_get_visitor_location') ) {
      $locationAsArray = ip_geoloc_get_visitor_location();

      // debug
      //dpm($locationAsArray);

      if ( isset($locationAsArray['locality']) ) {
        $locationAsString = t($locationAsArray['locality'].", ".$locationAsArray['country']);
      }
    }

    $submittedLocationAsString = "";
    if ( isset($view->exposed_raw_input['field_geofield_distance']['origin'] ) )
    {
       $submittedLocationAsString = $view->exposed_raw_input['field_geofield_distance']['origin'];
    }

    // debug:
    //drupal_set_message( "submitted location is: ".$submittedLocationAsString );
    //drupal_set_message( "actuallocation is: ".$locationAsString );

    if ( $locationAsString == $submittedLocationAsString )
    {
      $view->build_info['title'] = "We think you're near ".$locationAsString.". ".$thereAreAsString." here.";
    }
    else
    {
      $view->build_info['title'] = $resultsAsString." near ".$submittedLocationAsString;
    }

```

**My ideal solution**

But as you can see, this straight compare is not necessarily that robust. To determine the title I want, I think it may actually be better to insert a hidden field in the form, in `hook_form_alter` and detect the value/presence of this field in `cgformutils_views_pre_render` \- is this approach within convention and not 'illegal' or bad practice?

# Answer
Though I am providing the solution for the question which you have asked but as per your description I understand you are looking to achieve content boosting with views.

It's a nice idea which has been implemented on some websites like meetup.com, where they boost the local event at top when you visit & these works for anonymous users too as well as authenticated.

You will need 3 modules to achieve this - Location, Smart IP & Views.

I have written a blog post about configuring them to achieve this, which you can find at - http://drupalconnect.in/content-boosting-views

I will recommend you to try this if you trying something like this :)
> 0 votes

---
Tags: 7, forms
---


# Question
Title: View of file entities, sorted by upload date, reorders when updating a file
I have a view of file entities, sorted by **upload** date. When I edit one of the fields attached to one of my files the upload date of the file gets updated. The view now shows the last *modified* file first and no longer the last *uploaded*. Is this the normal behavior? Is there a way to actually sort my view by *upload* date?

# Answer
> 1 votes
A quick check with `drupal_get_schema()` confirms that file entities have only one associated time column called `timestamp`; there is no separate "upload" and "modified" date. So that timestamp, presumably, gets updated every time the file entity gets saved.

This makes sense from a certain standpoint because editing a file entity could involve updating the file itself.

I decided to take a crack at a custom module that would add a new "upload date" column to the file entity table. This may be completely wrong, and I haven't tested it, so do NOT try to use it on a production website until you're sure it works, but it might just give you what you're looking for.

In `mymodule.install`:

```
function mymodule_install() {
  // Add a column to the file table for your new creation date field.
  db_add_field('file_managed', 'upload_date', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0
  ));
  // Load all existing files and set their upload date to be equal to their current timestamp.
  $files = entity_load($file);
  foreach($files as $file) {
    $file->upload_date = $file->timestamp;
    file_save($file);
  }
}
// Drop the new field if the module is uninstalled.
function mymodule_uninstall() {
  db_drop_field('file_managed', 'upload_date');
}

```

In `mymodule.module`:

```
// Set the upload time field to the current time when the file is first saved
function mymodule_file_presave($file) {
  if(!isset($file->upload_date) || $file->upload_date == 0) {
    $file->created_date = time();
  }
}
// @TODO make the upload date field editable.

```

In `mymodule.views.inc`:

```
// Add a field handler for your new field.
function mymodule_views_data_alter(&$data) {
  $data['file']['upload_date'] = array(
    'title' => t("Upload date"),
    'help'  => t("The date the file was first uploaded."),
    'field' => array(
      'handler' => 'views_handler_field_date',
    ),
  );
}

```

Assuming that I didn't screw up, once the module is installed you'll need to add the upload date field to your view and use it for sorting.

---
Tags: views, files
---


title: Changing the menu active-trail depth

text:
# Question
Title: Changing the menu active-trail depth
So it looks like drupal menus only have a active trail depth of one, which is problematic for my nested pages since my menus wont be marked active once I drill into the nest. Is there a module or setting to fix this?

What I mean is if I have the following pages:

```
about/board-directors/john-smith

```

and a menu that shows:

* about
* board of directors
* something else

I could be on "about" and the about link would be active. I could be on "about/board-directors" and 'board of directors' would be active. But If Im on the page "about/board-directors/john-smith" I would like the 'board of directors' menu item to be active. How can I accomplish that? Im a bit of a noob so I'm in the dark here.

# Answer
> 2 votes
The Menu Trail By Path module will accomplish this:

> Menu Trail By Path sets the active-trail on menu items according to the current url.
>
> For example if you are at yoursite.com/blog/category1/article1 Menu
> Items with these paths will get the active-trail class on them and expand accordingly.
>
> blog
> blog/category1
> blog/category1/article1

# Answer
> 0 votes
I think that Menu block will answer your requirements, check it out. Here is a quote about it (from the module's project page):

> ... have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
>
> Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
>
> So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).

---
Tags: 7, routes
---