# Question
Title: Finding data using MySQL queries in the Node tables
Outside of the Drupal system I am trying to get user data based off of the user table and export this information into a CSV.

I'm not quite understanding how the Node table system works and where to get my data let alone how to Join it in MySQL manually.

I have my users table, the standard users table from Drupal. I'm trying to get data from quite a few tables for the user, a simple one line profile type data per user. Under a regular database structure setup it would be as simple as a few joins to the right xref ids and tables and you're good to go. It's not quite working here of course.

One of the tables in question is called `field_data_field_sexo_meta`. This holds the information if the user is Male or Female.

As you can see the field `field_sexo_meta_value` holds the information. But I do now know how to join this table to the user ID.

I've tried quite a few tables to get the user ID to link to this `entity_id` field but nothing as of yet has worked. For instance I've tried `field_data_field_paciente` which has these fields:

The last field there is the `uid` field, but this doesn't link anything either.

I've also tried linking to the column `uid` in the `nodes` table and a `type = 'termometro'` but also it doesn't link to anything and I get `null` on my joins.

So evidently I'm missing which table links the `field_data_field` tables to the users.

This is my current query:

```
SELECT
  u.uid,
  u.name,
  u.mail,
  ur.rid,
  n.field_su_nutricionista_es_uid,
  s.field_sexo_meta_value
FROM users AS u
  LEFT JOIN users_roles ur
    ON (ur.uid = u.uid)
  LEFT JOIN field_data_field_usted_es p
    ON (p.field_usted_es_uid = u.uid)
  LEFT JOIN field_data_field_su_nutricionista_es n
    ON (n.entity_id = p.entity_id)
  LEFT JOIN field_data_field_sexo_meta s
    ON (s.entity_id = p.entity_id)
WHERE ur.rid = 5
     OR ur.rid = 4
GROUP BY uid

```

# Answer
The concept that you are missing is that field data can be on any Drupal entity, nodes, users, etc. This means that when you `JOIN`, you need to add in some additional clauses. In particular, you need to check the entity type in the field data, as the entity ID isn't unique across entity types. You also need to check that the field value isn't deleted. So, you would have something like

```
LEFT JOIN field_data_field_usted_es p
  ON p.entity_id = u.uid AND p.entity_type = 'user' AND p.deleted = 0

```

Those three columns are typically all on need to `JOIN ON`. The rest of the columns would be what you return in the query, or use in a `WHERE`.

Most of the time, it is easiest to build up a query with Views, preview the SQL, and then use that as your starting point for a query outside of Drupal.

In your case, you could also use Views Data Export to generate your CSV inside Drupal itself.
> 2 votes

---
Tags: database, theming
---


title: Adding VBO to an entity

text:
# Question
Title: Adding VBO to an entity
I have created an entity. I have exposed it to views using `hook_views_data()`. I can create a view for my data however when I try and add a field for `Bulk Operation` there is not a field listed for my entity type.

How do I expose my entity to VBO?

# Answer
In your `hook_views_data` implementation, you need to specify that the table is about an entity.

You need to define the entity first. I assume you have already defined your new entity using `hook_entity_info`.

```
<?php
function hook_entity_info() {
  return array(
    'my_table_item' => array(
      'label' => 'My new entity item',
      'base table' => 'my_table',
      'load hook' => 'my_table_item_load',
      'entity keys' => array(
        'id' => 'mtid',
        'label' => 'My new entity item',
      ),
    ),
  );
}
?>

```

Then, mention this new entity type in the `hook_views_data` implementation.

```
<?php
function hook_views_data() {
  $data = array()
  $data['my_table'] = array(
    'table' => array(
      'base' => array(
        'field' => 'mtid', // Primary field
        'title' => 'My new entity item',
        'help' => 'My Table',
      ),
      'entity type' => 'my_table_item', // <-- Important. Set the entity type here.
      'group' => 'My Table',
    ),
  );
}
?>

```

VBO will start to show actions that are type of `entity` in the available actions. To add new actions, implement hook\_action\_info.

```
<?php
function hook_action_info() {
  return array(
    'my_table_do_awesome_things' => array(
      'type' => 'my_table_item', // <-- New entity type here
      'label' => t('Do awesome things'),
      'behavior' => array('changes_property'), //<-- Triggers an entity save.
      'configurable' => FALSE,
      'vbo_configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}
?>

```

I'm the first author (improved by the community later) of VBO for Drupal 7 drupal.org documentation. Have a look at it as well, for a deeper explanation for `hook_action_info` and making them configurable at VBO level.
> 2 votes

---
Tags: 7, entities, views
---


title: Can't group by year from a date row

text:
# Question
Title: Can't group by year from a date row
I have a field of date-time type. I added this field into a view and formatted the date-time field to show only year. When I switch 'aggregation' on in Views and try to group this field it didn't work as i expect and show all the dates again. I saw the Vies-query and there wasn't any preformatting. It was grouping by dis field only. I want the modify the query to get this fields formatted as i need(years only). Any advices would be appreciated. Thanks in advance!

# Answer
I don't think (I haven't seen your view) you need to enable aggregation to group by year. This is a solution:

1. If you need to display the date field value add the field twice. You will use one for the display of the date and the other for the grouping by year. If you are not going to display the date, you still need the date field to be able to group by year.
2. On the date field you are going to use to group by year you need a custom format that will only show you the year and if you are collecting both start and end date set it to you only the start date or the end date, but not both.
3. To create a custom date format go to admin/config/regional/date-time in Drupal 7 or to admin/settings/date-time in Drupal 6. There you will create a date format that will only show the year and then create a date format type that will show that date format.
4. Back to the date field you want to use to group by year change its format to the newly create format that only show you the date and set you show only one date and click apply. Also if you don't want the year value to show on the view check the option to exclude it.
5. Depending on the view format you have chosen (Table, Unformatted list, HTML list, etc) you will click the setting of the format and you are going to set the date field with the newly date format as the grouping field. Click apply and you are done.
6. You might also want to visit the "sort" section of your view to set the sort order of the dates.
> 1 votes

# Answer
If you use aggregation in views you MUST remove all sort options or else it won't group.
> 0 votes

---
Tags: 7, views, datetime, css-js-aggregation, entities
---


# Question
Title: StringOverrides doesn't change the text in DCommerce "Add to Cart" Button
Seen a lot of references to the hook\_form\_alter function on how to apply this, but many of the posts are aimed at more seasoned developers. I know enough to know that I need either a custom module to change these, but I don't know where to find the form id's on the buttons to change.

I was also pointed in the direction of the StringOverrides module, but this doesn't effect the changes I want on the buttons, only where the terms I want appear in plain text, as opposed to what I'm learning is hard-coded into the Commerce Modules.

So...a) how do I find the form ids to make a module to change these buttons? and b) how to get String Overrides to actually change the text on the buttons?

# Answer
> 1 votes
The fields I was trying to change ended up being hard-coded into drupal commerce, such that string Overrides, and even the Commerce Cart Overrides modules didn't help me get done what I needed to do completely.

So...I applied the hook\_form\_alter() functions in the bartik theme, because I couldn't get them to work in a stand alone module, although from what I read this would be better practice and then you don't have to remember what you changed where if you want to change themes etc.

So, combination approach got done what I needed in the end. Have to say, overall documentation is pretty opaque for a relatively easy fix and from googling, a relatively around a common problem.

Code snippet that might help:

```
function bartik_form_alter(&$form, &$form_state, $form_id){
dpm($form_id);
dpm($form);
if (commerce_form_callback($form_id, $form_state) == "commerce_cart_add_to_cart_form"){
$form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value']=t("Add to Inquiry List");
}
if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
$form['actions']['submit']['#value'] = t("Update List");
$form['actions']['checkout']['#value'] = t("Submit List");
}
if(strpos($form_id, 'commerce_checkout_form_checkout')===0){
    $form['buttons']['continue']['#value'] = t('Proceed to final list submission.');
    }
if(strpos($form_id, 'commerce_checkout_form_review')===0){
    $form['buttons']['continue']['#value'] = t('Submit your inquiry list');
    }

```

}

---
Tags: commerce, string-overrides
---


title: Drupal 7 ajax callback never ends

text:
# Question
Title: Drupal 7 ajax callback never ends
I'm trying to do an ajax callback on page every load with drupal to get some info. The problem is that when the ajax callback is done and the data processed, Drupal continues calling the ajax function once and over again adding the typical "Please wait..." text repeatedly.

The javascript:

```
(function($){

  Drupal.behaviors.myModule = {
    attach: function () {
      var settings = {};
      settings.url = '/my_module_ajax_callback';
      settings.event = 'onload';
      settings.keypress = false;
      settings.prevent = false;

      var base = 'myModule';
      var ajax = new Drupal.ajax(null, $(document.body), settings);
      Drupal.ajax[base] = ajax;

      $(ajax.element).trigger('onload');
    }
  }

})(jQuery);

```

The php:

```
<?php

function my_module_init() {
  drupal_add_library('system', 'drupal.ajax');
}

function my_module_menu() {
  $items['my_module_ajax_callback'] = array(
    'page callback' => 'my_module_ajax_callback',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_block_info() {
  $blocks['my_module_block'] = array(
    'info' => t('My Module Block'),
  );
  return $blocks;
}

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

  $block['content'] = '<div id="my_div">This data must be replaced by ajax</div>';

  return $block;
}

function my_module_ajax_callback() {

  $commands[] = ajax_command_replace('#my_div', '<div id="my_div">This data has been replaced by ajax</div>');

  $page = array('#type' => 'ajax', '#commands' => $commands);

  ajax_deliver($page);
}

```

Seems the ajax callback is never complete.

In misc/ajax.js:

```
complete: function (response, status) {
  ajax.ajaxing = false;
  if (status == 'error' || status == 'parsererror') {
    return ajax.error(response, ajax.url);
  }
},

```

I don't know what I'm doing wrong. I really appreciate your help. Thanks.

# Answer
I've found a solution myself. Seems after the ajax callback the attach function is called again, so I surrounded by a jQuery **.once()** method:

```
(function($){

  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      $('#my_div', context).once('my_div', function () {
        var elem_settings = {};
        elem_settings.url = '/my_module_ajax_callback';
        elem_settings.event = 'load';
        elem_settings.keypress = false;
        elem_settings.prevent = false;

        var base = 'myModule';
        var ajax = new Drupal.ajax(base, this, elem_settings);
        Drupal.ajax[base] = ajax;

        $(this).trigger('load');
      });
    }
  }

})(jQuery);

```

This prevents calling the ajax once and over again.

https://drupal.org/node/756722#jquery-once

https://drupal.org/node/2192041
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Can't get narrow stylesheet to load in Omega commerce sub-sub-theme
I've got a sub-sub-theme of Omega, namely, a subtheme of omega\_kickstart\_theme, which is in turn a subtheme of omega\_kickstart, which is a subtheme of omega.

Here's my .info file (pastebin).

I've stuck the file freshstop-omega-alpha-default-narrow.css in the /css folder, and that's supposed to be all she wrote. It's supposed to load for the narrow layout.

But when I resize my browser and check for this file, it's not there, nor are its styles. Cache cleared, css aggregation off, etc. Firefox.

I've also tried freshstop\_omega-alpha-default-narrow.css (note underscore instead of dash).

Hmm. Any deeper tips? Place to start debugging?

# Answer
So it turns out freshstop-omega-alpha-default-narrow.css actually IS being added, just not at the breakpoint that I expected.

The problem is that I'm thinking from a more "mobile second" perspective. Here's the stylesheet cascade:

* global.css
* example-alpha-default.css
* example-alpha-default-narrow.css
* example-alpha-default-normal.css
* example-alpha-default-wide.css

**"Narrow" is included at 720px and wider**, while global.css is included at all sizes. If one wants to target just mobile or smaller, one would have to create a new media query.

More information here: https://groups.drupal.org/node/156719
> 0 votes

---
Tags: theming, commerce
---


# Question
Title: Why is my theme's block preprocess function not reordering elements?
I'm trying to do something that seems fairly basic, but I'm having loads of trouble.

The drupal search\_form block outputs an input field and a submit button, in that order. I'd like to swap the order of those fields. I'm using `theme_preprocess_search_block_form` to attempt to reverse the order. This is my current function:

```
function mytheme_preprocess_search_block_form(&$data)
{

    $data['form']['search_block_form']['#attributes']['placeholder'] = 'Search ...';
    $data['form'] = array_reverse($data['form']);
    foreach(element_children($data['form']) as $k) {
        if(!empty($data['form'][$k]['#weight'])) {
            $data['form'][$k]['#weight'] *= -1;
        }
    }

    $data['form']['#sorted'] = FALSE;
}

```

This function *does* get called, since a `var_dump` will output to the browser, however, the changes don't make it to the front end. So, what is unchanging my changes?

# Answer
I figured this out. Drupal can be so infuriating when you are new to it.

The rendering of the search\_form\_block was happening in a template function file:

`bootstrap-search-form-wrapper.func.php.`

containing:

`function bootstrap_bootstrap_search_form_wrapper($variables)`

The function customizes the rendering of the search form by calling out elements specifically - thus ignoring `'#weight'`; the wrapper function is part of the bootstrap theme.

The solution is to overwrite the bootstrap theme function with a similar function in our child theme: `function mytheme_bootstrap_search_form_wrapper($variables)`

o.O

Hopefully this helps someone.
> 0 votes

---
Tags: search, theming
---


title: Drupal Bulk Update Nodes using button

text:
# Question
Title: Drupal Bulk Update Nodes using button
I have view that displays a table of node for the current user.

I am confused as to how i can provide the functionality to bulk update certain values.

For example:

I have table of nodes (custom content type=List) and that content type has a custom field called list\_status.

I want to update the value of the list\_status for all the selected nodes.

I looked at VBO (Views Bulk Operation) to do this, i managed to do it with "Modify Entity Value" setting but the UI/UX i get with this is not what i desire. It takes me to a new page to select the value.

What i need to do is is run this action on a button click. I would really appreciate if some one can please help me figure this out?

I felt, i would only be able to accomplish this by doing something custom with my own module but if i am right, then a starting point for this would also be just as much appreciated.

# Answer
I seem to have solved my issue, i will try to elaborate for future reference and also for any one who may need this.

First, it seems i missed the "Bulk operations settings" section as it was collapsed by default. But one of the options under it is "Display operations as" which provides two choices (1) Dropdown selectbox with Submit button and (2) Each action as a separate button

The second option was what i needed to get the buttons i wanted.

Then for bulk updating a custom field of my content type, i added **hook\_action\_info()** into my custom module and created a custom action that would become visible where the "Modify Entity Value" option was.
> 0 votes

---
Tags: nodes, views
---


title: Best Practice for Page Efficiency

text:
# Question
Title: Best Practice for Page Efficiency
I was wondering if anyone knew which of the following is most efficient (or an alternative if applicable). The idea is to create a header containing information for a specific node. This assumes all other variables, such as caching being equal. This would be for a Drupal 7 install.

i) Create a block, restricting it to the specific node

or

ii) Create a custom tpl with the information hard-coded (I know it's a Drupal no-no)

Using a block is simpler to deal with and update for obvious reasons, but I was curious if there was any significant difference in page rendering time, or resources used, etc.

# Answer
> 1 votes
A custom template always results in better performance. Views and blocks are stored in the database which need to be queried and rendered first. Whereas templates require less memory and cpu because the php can be executed directly. When using a template you also have the advantage of SCMs like git or subversion.

The performance difference between templates and blocks won't be noticeable as soon as you enable caching on your site .

So what should you use? It is completely depending on the case. If your header will be shown on multiple pages, i'd go with a template. If you'll show it only on seperate pages (whitelisted urls), I'd go with the block.

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


title: Include dynamic tagging in drupal7

text:
# Question
Title: Include dynamic tagging in drupal7
I just like the way the tags work out in stack exchange communities. The way it gets description for each tag in a dropdown and key based tagging.

How come it works?? Do we need to use jQuery???

I just want to know whether these kind of tags can be developed in Drupal 7

Is there any module in Drupal 7 to make our tags appear like the one shown in the above image.

# Answer
> 1 votes
Drupal out of the box supports taxonomy and tagging using autocomplete. You need to create a vocabulary and add terms to the vocabulary.

Create a term reference field and choose widget as autocomplete.

Regarding making it look alike above you can consider this post.

---
Tags: taxonomy-terms, nodes, javascript
---


# Question
Title: How do you give the content of a node a margin/padding without using html within the node?
How would you go about giving an entire node (the content) a margin or padding to the edge of the node - without using html within the node - in drupal?

1. Is there a module for this?
2. If not - how do you do so using CSS?

# Answer
it varies per whatever theme you use. it's typically something like div.node or div.node div.content as an example. tools like Firebug and Chrome developer tools can show you what classes a piece of content has in your HTML page. Using DisplaySuite for example you could provide additional classe(s) to any piece of content within view\_mode -- but the basic markup exists per theme to target a nodes output on the screen.

It not only varies per whatever theme your using, but if your theme is HTML5 vs HTML4 (why in this day in age, i dunno) it may be `article.node` as a CSS selector because `article` is a new HTML5 element type, vs say a plain old `div.node` in older versions of HTML.
> 1 votes

---
Tags: nodes
---


# Question
Title: Spam url_alias entries being created - how do I stop them?
I'm using Drupal 6 and having trouble with url\_alias spam.

Somehow spam entries are showing up in the url\_alias table as aliases for valid content.

I thought an administrator or valid user would have to create these. I don't understand how they're appearing for content that I created.

I appeared to have stopped spam registrations using a combination of Mollom, honey pot and spamicide. I can't figure out how the url\_aliases are appearing.

Can anyone give me a good place to try to start figuring this out?

Thanks, Joe

# Answer
> 0 votes
Who have access to *Administer ➔ Site building ➔ URL aliases* depends on how you've set access to the permissions `administer url aliases` and `create url aliases` under *Administer ➔ User management ➔ Permissions*. If you've granted access to the *Anonymous* user role, everybody can do it. If you've granted access to *Authenticated* user role, a rogue authenticated user can do it.

First, check out these permissions and make sure they are safe. Leave them unchecked for all roles. Then, only the super admin (user #1) can create aliases using the GUI.

If these setting are secure, and you *still* get unwanted `url_alias` entries created, then some outsider has gained direct access to your database. That's bad.

Finding the cause of database intrusion is not easy. Possible attack vectors are: A bad module that permits SQL injection, some means outside of Drupal (an inscure *phpMyAdmin* is the most common cause), or (in particular if you're on shared hosting) a host misconfiguration.

However, without having direct access to your site's and its log for forensics, it is impossible to know how an outsider has gotten into your database (if that is indeed the cause).

---
Tags: path-aliases, uri, advertising
---


# Question
Title: Sending email notification based on flagged node being linked via entity reference
I need to send an email notification to followers of a node, when another node that is linked, has been created.

Example:

* Users follow "location" type (e.g London) by flagging that node using the flag module and 'follow' type.
* Author creates a "blog" type (e.g. Things to do 2014!) and links it to their location via field\_location \[entity reference\].
* When published, send email to all followers of the "location" type.

Can anyone recommend the way to do this with rules or point me in the right direction?

Thanks, Paul.

# Answer
> 0 votes
I found the answer to this, or at least, *a* way to do this. In a custom.module:

Firstly, this checks if something is required to happen (creating a 'blogpost'), and if so, then gets the NID of the item the user is following (e.g. field\_linked\_item).

```
function custom_node_presave($node) {
if ($node->type == 'blogpost' && $node->is_new) {
    $linked_node_nid = $node->field_linked_item['und'][0]['target_id'];
    if ($linked_node_nid) {
      $emails = custom_get_blog_follower_emails($linked_node_nid);
      if ($emails) {
        custom_schedule_mass_email($linked_node_nid, implode(',', $emails), 'email_blog_post_linked');
      }
    }
  }
}

```

This function gets the email address for all users who flagged the blog that is linked to this blogpost (via linked\_item) and returns the list to the function above:

```
function custom_get_blog_follower_emails($nid) {
  $query = db_select('flagging', 'fc');
  $query->join('users', 'u', 'fc.uid = u.uid');
  $query->join('flagging', 'fc2', 'fc2.entity_id=fc.entity_id AND o.entity_type=\'node\' AND fc2.fid=5');
  $query->leftJoin('field_data_field_opt_out', 'o', 'o.entity_id=u.uid AND o.entity_type=\'user\' AND o.deleted=0');
  $or = db_or();
  $or->condition('o.field_opt_out_value', 0);
  $or->condition('o.field_opt_out_value', NULL);
  $result = $query
    ->fields('u', array('mail'))
    ->condition('fc.entity_type', 'node')
    ->condition('fc.entity_id', $nid)
    ->condition('fc.fid', 4)
    ->condition('u.status', 1)
    ->condition($or)
    ->orderBy('fc.timestamp', 'DESC')
    ->execute()
    ->fetchCol();
  return $result;
}

```

If email addresses are found by the function above, the original function then uses this to send emails via a pre-created rules message:

```
function custom_schedule_mass_email($nid, $to, $action) {
  $state = new RulesState();
  $state->addVariable('nid', $nid, array('type' => 'integer'));
  $state->addVariable('to', $to, array('type' => 'text'));
  $task = array(
    'identifier' => 'custom_' . $action . '_' . $nid,
    'date' => time(),
    'config' => 'rules_' . $action,
    'state' => $state,
  );
  rules_scheduler_schedule_task($task);
}

```

You need to create a rule to accept the 'to' and 'nid' (nid in my use is to allow rules to get some information about that post). In my case, the rule is called 'email\_blog\_post\_linked'.

This is pretty specific to my requirements, but hopefully it will point people in the right direction.

---
Tags: 7, rules, flags
---


title: drupal theme not show in appearance

text:
# Question
Title: drupal theme not show in appearance
My new drupal theme zeropiont isnt showing up in drupal 7. I placed zeropint drupal theme in the /sites/all/themes or sites/default/themes directories. It is not showing into appearance.

# Answer
Now your theme should be listed
> 1 votes

---
Tags: theming
---


# Question
Title: What are the 'todos' when your database is hacked?
I want to plan for the terrible nightmare of my database being stolen. I feel I am secure, and I am not holding much actual data, but... if it does get taken - what do we do, is there a standard way of drupalists to respond?

I am looking for specifics where obviously required, e.g. 'reset all passwords', but how?

Paul.

# Answer
In Drupal 7, while all passwords are hashed (`SHA-2 with 64-bit words`) *and* salted, if your user's passwords have low entropy, brute-force password attacks are feasible.

Image source: xkcd, explanation.

Also note that the cartoon above assumes that an attacker tries to brute-force passwords *over the web*. As pointed out by @Damon in a comment:

> Readily available brute-force crackers check 200-500 million hashes per second on a single commodity PC, not 1000. That means a 44-bit password doesn't even last half a day, and a password as 99% of users will realistically have will last 1-2 seconds at most.

This means that if you experience a breech, you should force your users to reset their passwords, there's is the Force Password Change module that will invalidate all passwords and force users to set a new one.

There is also the Password Policy module that let you set a policy to force users to pick a password that is hard to crack by brute force (but it tends to enforce the type of policies the xkcd cartoon above lampoons, so I am not a big fan of it).

In addition to these modules, there is a recipe on Drupal.org to create a drush command to change passwords on accounts that are not actively used that may be used to invalidate passwords for stale accounts.

You may also condsider making your site less vulnerable to password cracking by adding Two-Factor-Authentication.

To guard against PHP injection, you may want to install the Paranoia module.

> The Paranoia module attempts to identify all the places that a user can evaluate PHP via Drupal's web interface and then block those. It reduces the potential impact of an attacker gaining elevated permission on a Drupal site.

To monitor your site and detect unauthorized changes, you may want to install the MD5 Check module.

> The MD5 Check generates a md5 checksum of all module files. If module is changed a critical security error is generated in watchdog log.

There may be other sensitive data in your database beside passwords (e.g. credit card numbers, medical records). If you're really worried about your database being stolen, you need to encrypt sensitive data stored in the database. The Encryption module helps you defend sensitive data by means of symmetric encryption.

The the *Payment Card Industry* PCIComplianceGuide.org AFQ provides guidelines for what you should do if your site stores sensitive data. It also links to guidelines for dealing with data breeches.

Depending upon your location, yoy may have to report a data breach to affected parties. In the EU/EEA, this is mandated by the Privacy Directive. In the US there are now over 38 states that have privacy law that mandates notification. See www.privacyrights.org for more details.

Acknowledgements: Thanks to @Damon for pointing out that even 44 bits of entropy may not be good enough these days. Thanks to author of Cracking Drupal and Security Team member @greggles for bringing the *Drush* command to invalidate old passwords and the *Parnoia* module to my attention. Thanks to @Ben for making me aware of the PCI guidelines.
> 10 votes

---
Tags: 7, security
---


title: Show full post on front page?

text:
# Question
Title: Show full post on front page?
When I publish to the front page, it shows part of the posts. My posts consist of just a file upload. However, the user must click on the post/click on the "Read more" button to see the file upload. How would I make Drupal display this file on the front page within the post?

# Answer
If you are using Drupal 7 you may change the teaser format for the content types promoted on front page. Navigate to "Home » Administration » Structure » Content types » YOUR CONTENT TYPE » Manage display" and click the "teaser" sub tab; then change the format for the body field from "Summary or trimmed" to "Default".

Notice that this will affect some other pages (taxonomy and views).
> 7 votes

# Answer
I would replace the frontpage with a view provided by the Views module; there is even a default View that comes with the module. Initially, it emulates the standard frontpage, but is far more configurable. I can't post a full "How to use Views" answer here, but in short, what you will want to add is a "Field", pick the "File" category, and there you can output a direct link to the file.

Video series about using Views.
> 1 votes

# Answer
ya.teck and kiamlaluno are correct except that you may not see a "teaser" tab. If this is the case, then be sure to check the custom display options for your content type and activate "teaser" - it should be one of the check boxes available. Then save the content type and you should then see the teaser tab/button mentioned above.
> 0 votes

---
Tags: nodes
---


# Question
Title: naming convention for .tpl.php in drupal 7 for custom content type
I have created content type named **basepage** and have created content **test**
My page url is

> ?q=basepage/test

what should my .tpl.php page name
like (node--1.tpl.php)

# Answer
> 3 votes
Overriding `node.tpl.php` for a specific content type is very simple. The naming convention is `node--machinename.tpl.php`. For `machinename`, use the machine name of the content type with underscores replaced by hyphens. You can inspect the machine name if you navigate to Administration → Structure → Content types. If you just want the override to apply to a single node (as opposed to all nodes of this content type), add the path replacing all slashes in the path with a double hyphen.

Provided you want to override the *node* template for path *test*, your template should be named:

```
node--basepage--test.tpl.php

```

No extra actions are required. Just create it (usually by copying it from the theme's `node.tpl.php` to `node--basepage.tpl.php`), modify it and place it inside the themes `templates/folder`.

---

Provided you want to override *page* template `page.tpl.php` based on the content type being displayed, the naming convention is the same, but you need to do some extra legwork:

1. Open the template.php file in your theme for editing.
2. Look for a function called THEME\_preprocess\_page (replace THEME with the theme's name).
3. If this function already exists, you will need to add your code to it inside an if-statement that goes at the end of this function, just before the closing bracket Otherwise, if it doesn't exist, you'll need to create a new function.

This is how the function should look like:

```
function THEME_preprocess_page(&$vars) {
  // If the function already exists, just leave the code here intact, and add
  // the three lines below to the end.
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

Now, copy the theme's `page.tpl.php` to a file named `page--machinename.tpl.php` and place it inside the themes `templates/folder`.

Provided you want to override the *page* template for path *test*, your template should be named:

```
page--basepage--test.tpl.php

```

for Drupal 7.

---
Tags: theming
---


title: add last user IP in view

text:
# Question
Title: add last user IP in view
How to add last IP address for online user ( only last IP address ) and link to ban user IP address ?

i tried display all ip address but that showed to me all ip addresses from any time

i want show last ip address

# Answer
Because it needs lots of coding and building a new module I only give you the tips and the algorithm, you need to know how to build a module.

1. build a module and create a variable (called IP) using `drupal_get_variable`, in this way a variable will be created in the \`variable\`\` table.
2. for any user who visits your website, replace its IP address with the existing one (`drupal_set_variable`) in the IP variable (so far it is easy to implement).
3. you need output this variable in your `view`, so use the `hook_views_prebuild ($view)` hook function, get the IP and embed it in the view.
> 0 votes

---
Tags: views, users
---


title: Random Article Button

text:
# Question
Title: Random Article Button
I'd like to create a button on a menu bar that can generate a link to a random article from my blog posts (much like Wikipedia has). It's for a client, and they'd like to have this functionality on the site.

I had a theoretical solution: have a .txt or .xml file containing a list of all the URLs to each of the posts, with a "key" assigned to each of them. Then, when the user clicks the random article button, the current time (ex. 1:45) is hashed and mapped to a specific URL. I am fairly new to Drupal, however, I was wondering if there was some way to have the random article button use a .c file to execute these steps. The site is being hosted on a server that uses Apache 2, and I looked through some modules that were implemented in C code. I'm pretty new to all of this, and spent many fruitless hours searching for solutions. It would be great if someone could provide a link to an article that explains how to execute c files on apache or a better alternative method to achieve my goal!

# Answer
the module Views can do that:

> You need Views if
>
> 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.

set it up as a page of content with whatever settings you want. If you're not familiar with Views, look at the documentation and do a search - there are lots of tutorials out there.

To do what you want, you would Sort by Random, and set the Pager to a specific count of 1.
> 2 votes

---
Tags: 7
---


# Question
Title: I can't add new icons in CKEditor default toolbar
I can't add new icons (tabs) in CKEditor toolbar, in EDITOR APPEARANCE options. Whatever I choose it only gives me default toolbar. I tried all versions. What should I do?

# Answer
> 2 votes
If you have jquery\_update installed and using 1.8 you might also run into javascript errors if you are trying to move toolbar elements around. Temporary setting it to 1.5 (doing my changes and setting it back to 1.8) fixed the issue for me.

# Answer
> 0 votes
Turn off the toolbar and add icons manually. To turn off the toolbar go to the admin/config/content/ckeditor/editg and select 'disable' for 'Use toolbar Drag&Drop feature'. I am guessing that the toolbar misbehaves because CKEditor Module imports JQuery UI sortable lib that is already imported once by the core. As result, it causes js fatal errors. I am out of time to verify.

---
Tags: wysiwyg
---


# Question
Title: Contextual filters in taxonomy term ID (with depth)
I need to make a view that will show me the nodes of a content type inside a node of another content type filtered by a taxonomy term.

I have three content types. The first one is **Projects**, in which I've added some projects (title, body and images-shadowbox). The second one is **Projects Categories**, in which I have some categories like:

* houses.
* offices.
* etc.

The third one is **Services**, in which I've added the following categories:

* architecture.
* engineering.

I have added a "Projects" vocabulary with two items:

* Project 1.
* Project 2.

In each node of the "Projects" content type, I assign term of the Projects vocabulary. Each node of the "Project Categories" & "Services" can have more than one terms of the Projects vocabulary.

What I need is to preview under each "Project Categories" & "Services" node the relevant node "Project", filtered by the taxonomy term of the "Projects" vocabulary.

How can I achieve this?

# Answer
This is similar to another request: Contextual filter in taxonomy- Drupal 7

I've customized my answer to your specific requirements:

First thing you need to do is install the References module

When setting up your project content type, create a category node reference field and a services node reference field. This will tie each project to one or more categories and one or more services.

When configuring your view, you will need to create relationships between the project and service/category.
> 0 votes

# Answer
I have accomplished something similar with the following combination of modules:

(1) references: project/references This module lets you create relationships between nodes (regardless of whether they are the same content type or not) and between users (doesn't sound like you need this part of the functionality).

(2) node reference from url: project/nodereference\_url This module lets you add a link to a node to add related content.

In your case, I would create a content type (instead of a taxonomy term) for "Project" and create a node for each project (Project 1, Project 2, etc.)

Then, I would use node reference from url to put a link on the project page that would allow you to relate other content to it. So, in your case, you said that you already have content types for project categories and services. Your link would say something like "add project category" and when you click the link you would select one or more categories using whatever kind of widget works best for you (select list, multiselect, checkbox, etc.). The node reference url module will take care of connecting the two pieces of content to one another in the database.

BUT, in order for the related content to show up on the project page, you'll also need to install the EVA module: project/eva

Mustardseedmedia has a good tutorial on how to do this.http://mustardseedmedia.com/podcast/episode37

You'll still need the contextual filter but not in the way you are trying to use it with the taxonomy terms.
> 0 votes

# Answer
You should use EVA - Entity views attachment module.
> -1 votes

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


# Question
Title: How can I delete all field collection revisions?
I want to delete all field collection revisions of a specific field. I found deleteRevision for this job, but I don't know how to use it. (I couldn't find any example of it.)

Anybody know how can I delete all field collection revisions of a specific field?

# Answer
> 2 votes
Since you want to purge revisions on a field in a field collection and not an entire content type, your best bet is going to be doing this directly in phpMyAdmin. I don't know of any modules that enable you to delete revisions for a particular field but not the whole content type.

I would locate the field in question and run DELETE from field\_revision\_field\_yourfieldname.

Of course you should back up things before you run a delete query.

The data for nodes and node revisions are store in two different tables. The data for the node page is stored in field\_data\_yourfieldname. The data for the revision is stored in field\_revision\_field\_yourfieldname.

To illustrate this concept for you, I set up a fresh install of drupal (7.28) on my local machine and connected it to a new empty database.

I set up a content type called field collection demo and I added two field collections.

Since I'm not sure what your configuration entails, the fields I used may or may not be similar to your fields.

Then I created two sample nodes and edited both of them several times with revision tracking turned on. I mostly used lipsum text but for the last revision I typed meaningful text to help you see what's happening in the database.

Here you see that I have created the two nodes:

Here you can see the lipsum text in the original post.

Here you can see that I've created multiple revisions of the node.

And here you can see the meaningful revised text that is the most recent revision.

The next picture shows you how this data is stored in the database in the field\_revision\_field\_yourfieldname table.

You can manually delete one row from the table using the red "X" in phpMyAdmin. Look, for instance, at the last row in this table.

After I click the red "X" for that row, it is deleted.

You can see that now the revision that began with r2 is gone from the field\_revision\_field\_my\_fifth\_field table.

This removes the revision from the node's revision page. Notice in this picture, the field labeled "My fifth field" is missing.

But this does not affect the node's public view, because that data is stored in the field\_data\_my\_fifth\_field table not in the field\_revision\_field\_my\_fifth\_field\_table.

Therefore, I can safely delete all the revisions from the field\_revision\_field\_my\_fifth\_field\_table with the delete query (as I've done on my demo site) and still view the node with no problems:

All the revisions from the field "My fifth field" are gone on the revisions tab but the view tab remains unchanged.

If you wanted to delete all the revisions for all the fields that comprise a node collection, you would simply run the delete query for each of the field\_revision\_field\_yourfieldname tables in the database.

---
Tags: entities
---


title: Profile2 template for profile type?

text:
# Question
Title: Profile2 template for profile type?
I have alredy created profile2 type with machine name "user" and now i would to overide template, can someone explain me how i have to name my new tpl? i ve copied existing, and tried some rename variants, but i didnt find solution.

In google i didnt find solution too.

Here is link for module https://drupal.org/project/profile2

# Answer
To theme a custom template for profile2, try the following:

* copy profile2.tpl.php from your module folder, to your theme's template folder
* rename the file profile2--machine\_name.tpl.php (profile2--user.tpl.php)
* adjust the template as desired
* clear the cache
> 1 votes

---
Tags: theming, users
---


# Question
Title: How to sell credits as products, using commerce module?
The ideas is to allow users to buy credits through Paypal etc. and only using that credits, they can buy 'real' products. I appreciate your hints to set this up.

# Answer
Have a look at the Commerce Userpoints* project. It allows to buy things using userpoints and there is also a feature that allows to buy userpoints that is based on a custom product type and rules, so fully customizable.

It most likely doesn't everything that you need, but it might be a start.

There is also Commerce credits and more similar projects, but I haven't tried them out, no idea what exactly they do and how well they work.

\*Disclaimer: I am the maintainer of the Userpoints project and I was also involved in that project and still have some code lying around to re-work the UI and improve it.
> 3 votes

# Answer
There is some documentation in the works for commerce credits module. Until it is committed you can preview it here: https://drupal.org/files/documentation-1629470-5.patch
> 1 votes

---
Tags: commerce
---


# Question
Title: how to bypass video conversion for mp4 files?
I am using the Video module on my site, and would like a would like to bypass video conversion and a user uploads a file in MP4 format.

Is there any way that the bypass video conversion?

The reason for this is that due to the high volume of video submissions, and the fact that most often the video is already mp4. The conversion takes a lot of hard drive space, and also required a lot of RAM and CPU resources. I am hoping that bypassing some of the unnecessary conversions will help alleviate this problem.

# Answer
> 0 votes
If you haven't already, look at these options under admin/config/media/video

* Bypass video conversion

(Bypass video conversion when creating videos.)
* Video convert on node submit

(Convert videos on node submit will enable by default for all users.)

---
Tags: 7, files
---


# Question
Title: Create send user private message link in a node template content type
How do you print the private message link in a node template please?

This what I've tried

```
hide($content['field_privatemsg']);

print render($content['field_privatemsg']);

```

Many thanks for your help

# Answer
> 1 votes
Assuming you want to create a link to the author, you should be able to create a simple link in the template \- Field that links to a path/url defined with Tokens, is it possible?

It would follow something like: http://www.example.com/messages/new/\[node:author\]

You can see a list of tokens here: https://drupal.org/node/390482#token-node

---
Tags: privatemsg
---


# Question
Title: Is there a way to add the comment section to the node edit page?
I am developing a site which will be used for information gathering. All views are designed to send users to node edit pages (instead of node view pages) so that they can see and update information at the same time. I would like to use the comment system, but I have not been able to figure out (yet) how to enable the comment section on a node edit page. This section show up on the node view. I would like to know if there is a way to make it show up on the node edit page as well.

# Answer
> 0 votes
Take a look at this for setting up a custom edit template if you don't want it site wide: http://www.nybergtechnology.com/blog/2013/11/11/how-create-edit-tpl-node-type-drupal-7

then you should be able to add:

```
<?php print render($content['links']); ?>  // only if you want the links to show

<?php print render($content['comments']); ?>

```

to the bottom, to produce the comments. (I didn't test this, so it may be gibberish)

---
Tags: 7, comments
---


# Question
Title: Center the open layer map when in edit mode
i setup a map with openlayers, geofield, addressfield and geocoder.

I added a geofield to a node, with openlayers as the widget type, and use geocoder to get the geocode from addressfield.

when editing, user press the Find using Address field button and the map display with the marker if found.

the question: how to center the marker? If i set the zoom level higher (in Center and Bounds setting of open layer), the marker will not be shown (out of the visible map area).

# Answer
> 0 votes
you need to enable placeholderlayer in openlyers map with a marker of your choice. and then in behaviours you need to zoom to layer and enable placeholder layer and save.

---
Tags: javascript
---


# Question
Title: Qiuck tabs shifts the Openlayers map background layer
Im displaying the list of locations (address and map Openlayers + Geofield) using views. There is no problems when displaying view in ordinary way, but when the view is displayed inside quicktabs the background shifts about 100px in particular(top-left) direction from the place it should be.

Normal map display

Same location with shifted map background

Also, I noticed that after opening Developer tools in Chrome the grey zone without map disappears(fills up with map) and if you click on the map region the red point mark shifts back to the place where it should be.

Any ideas about how to fix this issue ?

# Answer
This is the css/jquery issue .inside a quick tab the map doesn't get load because it is display none initially .when you click on the locations tab it tries to get load but dos not get loaded . you need to play with jquery a little.
> 0 votes

---
Tags: 7, google-maps, javascript, blocks
---


# Question
Title: How do I pass contextual filters to a view via services
I have a view that accepts a contextual filter in order to return the correct results. I'm using Services 3 and Drupal 7. I'm able to create an endpoint, and retrieve the view via services. But it seems like there is no way to pass the contextual filter, because services\_views only has a retrieve method (which uses GET). Does anyone know if this is possible, and if so how it can be done?

# Answer
> 17 votes
pass your filter as follows: yourendpoint?args\[0\]=value&args\[1\]=value

Good luck

# Answer
> 4 votes
As long as the filters are exposed in the view, the fieldnames are available as contextual filters. For instance, expose NID in the filters list and you can do

```
GET /endpoint?nid=5

```

# Answer
> 3 votes
This is an already answered question, but for others browsing here in the future, I would recommend using and taking a look at the documentation at Services Views. It spells out how to pass contextual filters along with a bunch of other possible arguments, and it has a demo video and shows examples.

# Answer
> 2 votes
If you have to use multiple value in your contextual filter, I suggest doing the following :

* Create your Contextual filter (in my case : nid)
* Click on "Provide a default value" and set the type as PHP Contextual Filter expect a string with multiple value separated by a + or a comma.

`return str_replace("|", "+", $_GET['nid']);`

* In the "More" section, check "Allow multiple values".

Now when calling your service, provide your contextual filters that way : .../my\_service?nid=1|2|3

# Answer
> 2 votes
For those of you still having issues, ensure that when you add a Filter to the View, under the settings for the specified Field, there is a Filter identifier. This needs to be the argument passed into the querystring in the two formats listed on the Services Views documentation.

# Answer
> 1 votes
I was able to get a contextual filter with Drupal Services by: 1) enabling the 'Views Contextual Filter Query' module (https://drupal.org/project/views\_contextual\_filter\_query) 2) passing the contextual filter through the URL as a querystring.

In the contextual filter, you will have to select 'WHEN THE FILTER VALUE IS NOT AVAILABLE' -\> 'Query Parameter from the URL. You will then be able to add the parameter name which you will use in the URL. This also allows you to use the + and | characters for selecting multiple filter criteria.

---
Tags: 7, views, services
---


# Question
Title: Cache Backport not loading correctly. Unable to change cache.inc location?
Drupal 6, trying to get the Cache Backport module working. Every time I load a page, this error fires:

```
Call to undefined function _cache_get_object() in /var/www/sites/all/modules/cache_backport/cache_backport.admin.inc on line 60,

```

That is defined in `cache.inc` within the cache\_backport module's folder. It would appear that the file isn't being loaded. Here's the relevant portion of my `settings.php` file.

```
$conf['cache_inc'] = 'sites/all/modules/cache_backport/cache.inc';

```

Simple enough.

I'm using the Domain module and looking around the config files, I did notice references to cache but I can't really tell their purpose. Also, and this may or may not be related, but prior to trying the cache backport module I tried just doing the Drupal 6 memcache module and it never seemed to send anything to it. The memcache area in Reports would load, it was communicating with Memcached, but it never seemed to write anything to it. I feel like it was caused by the same thing.

# Answer
> 0 votes
The Domain module was in fact responsible for this. I moved `include './sites/all/modules/domain/settings.inc';` to the very end of my `settings.php` file and everything started working.

I then added the following code to ensure a different cache\_prefix for each of the domains.

```
$thishost = $_SERVER['HTTP_HOST'];
$site_arr = explode('.', $thishost);
$sitename = $site_arr[1] . '_';
$conf['cache_prefix'] = $sitename;

```

Credit for that code goes to Drupal 6 APC with domain access module not working for (sub-)domains. In fact, now that I look at that page again, I notice that he has the domain access include on the last time, too. Audible sigh. Don't know how I didn't notice that before.

It also appears that if you want to move Domain's settings.inc to the bottom, you need to make a tweak to that file. Modify `modules/domain/settings.inc` so the `domain_settings_setup_ok` function looks like this:

```
function domain_settings_setup_ok() {
  static $state = NULL;
  if ($state === NULL) {
    if (!empty($conf['cache_include'])) {
      $state = TRUE;
    }
    else {
      $state = !function_exists('cache_get');
    }
  }
  return $state;
}

```

That is an adapted version of the patch for D7 discussed at https://drupal.org/node/1240472.

---
Tags: 6, caching, database
---


# Question
Title: DB queries fast, Apache response slow, high PHP CPU
Working with D6, trying to get a page running more efficiently. I made a lot of progress by installing the Cache Backport module and configuring Redis, so devel shows my DB queries are a fraction of what they were before. Load testing shows that the site can handle a much heavier load than ever. Making progress.

The problem now is that the initial connection to the site is slow, usually 2-3 seconds but often as high as 5 or 6. It's not the database doing it, Devel shows queries are very fast, less than 500 ms on average. It seems to be pretty random. I'm working off a test server right now, I'm the only one on it, but I know it's not just me because any tests with external services show the same thing. My log files are clean, both Apache and syslog. The only other symptom I've seen is that prior to the page's load, PHP will spawn 6 processes and CPU will be high.

I've tried using XDebug to trace PHP's behavior but nothing is jumping out at me. It's definitely loading a few different files, including the Domain module, but I can't really tell what's happening.

I'm using fcgi, Debian 7, Apache is using mpm-worker, if that matters at all.

# Answer
I would suggest trying to use drupals caching to cache the page and installing a php caching system such as APC or OP cache (if using php 5.4 or higher for OP caching) and this should speed up significantly. If you really want a performance hit then try using varnish to cache the pages.

The reason is by default apache does not do a very good job rendering pages in the sense of requests per second and can significantly increase when caching and exponentially increase using varnish caching.

So in short the following is good for performance:

PHP: 1. ) APC cache or OP caching. 2. ) Varnish caching 3. ) MYSQL caching such as memcache
> 1 votes

---
Tags: 6, performance
---


# Question
Title: Sorting entities in a view by a field in a 'sibling' entity
At its most general, my question is how you can sort entities in a view by a field in a related entity. This is best illustrated with a lengthy example which is more specific, though still quite abstract. It describes sorting by 'sibling' or 'child' entities (depending on what you count the view as showing).

---

Suppose that you have entities in the following structure:

* Entity A1 (of entity type A\*) related to (colloquially, a 'child' of) entity U1 (of type U\*)
* Entity B1 (or type B\*) is also a child of the same entity U1

Here is my particular example:

* User P has 2 profile2 profiles, A and B

Now suppose you have a view of entities of type U\* (in my example, a view of users) - i.e. when first creating the view, you chose U\* (here, users) from the 'Show' menu. You've added relationships to A\* and B\* in this view, and made it show the name field of U\* (here, 'User: name') and the fields of A\*, filtered by a field in A\*. Given our specific entities, the view would show:

```
U1
A1 field 1
A1 field 2

```

This means that though this is a view of U\* entities in the 'i.e.' sense above, it could also be called a view of A\* entities in the sense that if you'd added B\* fields they'd show under a *duplicate* of the U\* name. Given our specific entities, the view would show:

```
U1
A1 field 1
A1 field 2

U1
B1 field 1
B1 field 2

```

This makes my example either about 'child' or 'sibling' entities.

Sorting the view by a field of B\* (e.g. B\* field 1) doesn't work. Applied to this abstract example, my question is how to make it work.

---

As requested in comments, here is the SQL query and results for an instance of this example. The SQL:

```
SELECT users.name AS users_name, users.uid AS uid, profile_users.pid AS profile_users_pid, profile_users__field_data_field_weighting.field_weighting_value AS profile_users__field_data_field_weighting_field_weighting_va, 'profile2' AS field_data_field_do_you_plan_to_donate_a_ce_profile2_entity_, 'profile2' AS field_data_field_if_so_to_which_causes__profile2_entity_type, 'profile2' AS field_data_field_if_so_until_when__profile2_entity_type, 'profile2' AS field_data_field_would_you_like_to_give_any_profile2_entity_
FROM
{users} users
LEFT JOIN {profile} profile_users ON users.uid = profile_users.uid
LEFT JOIN {field_data_field_do_you_plan_to_donate_a_ce} profile_users__field_data_field_do_you_plan_to_donate_a_ce ON profile_users.pid = profile_users__field_data_field_do_you_plan_to_donate_a_ce.entity_id AND (profile_users__field_data_field_do_you_plan_to_donate_a_ce.entity_type = 'profile2' AND profile_users__field_data_field_do_you_plan_to_donate_a_ce.deleted = '0')
LEFT JOIN {field_data_field_weighting} profile_users__field_data_field_weighting ON profile_users.pid = profile_users__field_data_field_weighting.entity_id AND (profile_users__field_data_field_weighting.entity_type = 'profile2' AND profile_users__field_data_field_weighting.deleted = '0')
WHERE (( (profile_users__field_data_field_do_you_plan_to_donate_a_ce.field_do_you_plan_to_donate_a_ce_value IS NOT NULL ) ))
ORDER BY profile_users__field_data_field_weighting_field_weighting_va ASC

```

The results:

```
Tom Ash
Do you plan to donate a certain amount either until you retire or until you die?:
Everything over £14,000 (~$22,000), and at least 10% of income
Weighting:
NO RESULT, BECAUSE SHOWING DIFFERENT

Tom Ash
NO RESULT, BECAUSE SHOWING DIFFERENT PROFILE
Weighting:
432

```

---

My research so far (~3 hours): Googling; looking through dozens of StackExchange answers; searching the Views issue queue; as had no responses here yet, added a support request in the Views issue queue.

# Answer
> 1 votes
(1) you cannot do this simply by editing the view, but (2) you can do this with a custom module. I expand on (1) and (2) below.

(1) holds because there is no single ;-terminated SQL query which will do this. The reason is that when you have 2 profile2 profiles the data you're fetching is spread across 4 tables structured like this. As you can see from that, the 2 profile2 tables reside in separate tables, and you can't tell that they belong to the same user except by checking a 3rd table. SQL queries simply can't manage this.

(2) is possible because a custom module lets you run multiple lines of PHP, drawing on additional query to fetch the field you want to sort by. You want to do this in hook\_views\_pre\_render. Here's a module I created to do something similar on an existing site I had: http://www.pastebucket.com/40183

---
Tags: views
---


# Question
Title: How to copy forum structure Advanced Forum?
I wish to use the Forum or Advanced forum module to create forums. But to save time I need to duplicate forum structure to create new ones. I've done Google search but did not find any useful information.

For example for a schools website, I can create another school just by copying a school structure that'll copy all child forums as classes which I'll not need to recreate.

Can anybody help me with this?

# Answer
What you should do is something like an Install Profile: https://drupal.org/developing/distributions

You can create Install Profiles from exiting sites with: https://drupal.org/project/profiler https://drupal.org/project/profiler\_builder

What I would do is make the first site exactly how you want it and then turn that into a Install Profile.

An easier way to do this if you have AEgir is to just clone your first site and then keep it as a template to clone others.
> 1 votes

---
Tags: nodes
---


# Question
Title: Multiple pieces of data attached to multiple states
I want to have two fields attached to each state a user selects on a multiple select form field - they can select as many states as they want.

Each state will then have a text field and a date field attached to it.

How do I do this? I can can't figure out a way to make this data optional.

So basically it would go as follows:

State textfield associated with state date associated with state

and this, up to 50 times, but optional aside from one instance.

# Answer
> 0 votes
The answer to this was the field collection module (alternatively, multifield can be used).

This allows you to create an unlimited amount of field collections, and served my purposes perfectly.

---
Tags: users, forms
---


# Question
Title: what function do i use to print out a menu? the menu was created in the admin
i have node that i simply want to display a menu. the menu itself is a list of archived articles, and was created in the admin.

i know how customize the node to do so, page--node--11.tpl.php.

i deleted the print render $content. so now, my pseudo code would look like.

print $archive\_menu;

or perhaps i need to call a function? can someone explain how to do this?

thanks

# Answer
> 0 votes
You can use menu\_tree\_all\_data function.

E.g.

```
$tree = menu_tree_all_data('machine-name-of-menu');
//menu_tree_add_active_path($tree);
print drupal_render(menu_tree_output($tree));

```

For more info go through the function documentation.

menu\_tree\_add\_active\_path will be found here. It will be used when you want to add active trail on menu.

---
Tags: theming, routes
---


# Question
Title: node not saved if I use drupal goto in submit
I want to know why node not save if I use `drupal_goto` in the end of `form_submit` function , it redirect to my page but the node not saved !!!

```
function mm_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "pre_register_node_form") {
 $form['#submit'][] = 'mm_submit_redirect';
}

function mm_submit_redirect(&$form, &$form_state) {
   drupal_goto('custom_path');
}

```

# Answer
> 4 votes
See internally when you save any node in drupal number of submissions comes to place. And once you will use `drupal_goto`, it will stop the process there, redirect you and will not execute rest of required functions. There is possibility where you are using `drupal_goto` function in your code, other submit handlers might be required in order to things work properly. If you call `drupal_goto` you would stop the execution flow and make it impossible for the other submit handlers to finish their thing. Now there is two way either you use some another approach for redirection or make sure your redirect submit handler (`drupal_goto`) is last.

I would suggest, you should use `$form_state['redirect']` instead of `drupal_goto`. Once I was using this function in my code and due to this automated cron stopped working, so I would recommend you avoid this function until you dont have other option because there is chance other submit handlers could be skipped, if this function not used properly.

**Use** `$_GET['destination']=$redirect_url;` instead of `$form_state['redirect']=$redirect_url;`.

---
Tags: forms
---


# Question
Title: Is learning Drupal 7 a bad option now after release of Drupal 8
Hi I am WeB developer and have recently started learning drupal 7. I have finished learning basics of PHP and have started learning drupal along with learning how to program the individual elements. Thankfully i have also got no. of materials ranging from books and video tutorials but what i also find is Drupal 8 has now also been released though i think it will take a lot of lot of time for people to build learning materials for that.

But i also think that it will take atleast 1.5 years to learn entire aspect of drupal and by that time Drupal 8 will be the worldwide adopted version.So do you guys think that learning Drupal 7 will be a waste as ppl will sign it off by then due to advent of Drupal 8. Please guide me on the same

# Answer
Well, firstly learning never gets wasted. Whatever you learn will some day in some moment help you.

Yes, Drupal 8 is going to be released and not yet released. No one knows when it gets released and even people are skeptic about the features that vary with Drupal 7. Definitely, Drupal 8 is going to set a new standard in development and usage. But, till then we shouldn't avoid Drupal 7.

Previously, we developed a website in Drupal 6 as soon as we deployed the site Drupal 7 was released. Then the features provided by Drupal 7 attracted us and we started migrating to 7 and it took most of our time in migrating. But our knowledge and work in drupal 6 didn't go into vain. Infact, we just learnt the new features added/upgraded. It took us only 1-2 days to know about Drupal 7, as we know the core concepts.

So, I suggest you to start learning drupal 7 don't bother about the things that are yet to come. You can easily manage things even drupal 8 gets released.
> 1 votes

# Answer
learning never gets wasted, most of the major principle remains same for Drupal 8. you will get more exposure learning many things and learn how to things different ways.

Yes, Drupal 8 is releasing soon, you can take all the benefits of core modules, but if you want more features and extended functionality you have to use contributed modules and not much contributed modules are there for Drupal8, developer needs time to write those modules for drupal8, you have to wait for that as well.

Decision is yours. I suggest you to go with Drupal7 and keep learning drupal8 as well.
> 0 votes

---
Tags: 7
---


# Question
Title: How to build route for entity without loading it?
I'm making a tree view of vocabulary terms and I need to link each term to it's page(depends on which link template name is provided as argument to my function).

I'm loading the terms with taxonomy\_get\_tree and I could get fully loaded entities with it but if the vocabulary grows this will impact performance. So I'm thinking if there is a way to get the route data to build links for the terms without the need to load the whole taxonomy term entities?

I could hard-code the routes because I know them but that would mean that for every new vocabulary or term link template the code would have to be changed which is not much of a solution.

So is there a way to build the route for the provided link template with only term ID?

# Answer
At least at the moment the route name used for the link is part of the entity type link templates. Once you have fetch that from the entity manager you just have to construct the route parameters for yourself and be relative save. I think it is fine, especially in your custom enviroment, to not rely that hard on other contrib modules.
> 1 votes

# Answer
Even in Drupal 7 https://api.drupal.org/api/drupal/includes%21common.inc/function/entity\_uri/7 you needed the full blown entity for the URI to it. There's nothing new here.
> 2 votes

---
Tags: 8, routes
---


title: How to add Main Menu to Menu Bar area?

text:
# Question
Title: How to add Main Menu to Menu Bar area?
This may sound a stupid question but as I have upgraded to D7, my main menu has disappeared and I could not figure out how to move it to corolla's 'Menu Bar' area (or anywhere else) . So appreciate your help.

# Answer
> 1 votes
Menus are not blocks, and as such cannot be placed in regions. Some themes don't render menus on their own, expecting you to place them in a region you prefer. Sounds counter-intuitive, but it can be solved.

To make menu a block, you can use Menu block module.

> It provides configurable blocks of menu trees starting with any level of any menu. And more!

Alternatively, you could use Nice Menus module:

> Nice Menus creates blocks that may be associated with any existing site menu which can be placed wherever normal blocks can be placed in a theme

Blocks the two modules are generating are different, but both can do the job. Test which one is better handled by your theme, and if both are good, use the one you simply prefer.

---
Tags: 7, routes, theming
---


# Question
Title: In which file should I write db_add_field function
I am writing a module for which I have to add a field to my database. So I need to use db\_add\_filed function, So in which file I should use this function? I mean should it be in .module file or .inc file?

# Answer
I think you should write your code for adding new field in DB in your .module file. Here is the code for you :

```
function xyz_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['node']['fields']['show_in_inbox'] = array(
    'type' => 'int',
    'length' => '4',
    'default' => '1',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by xyz module',
  );
}

function xyz_enable(){
    if (!db_field_exists('node', 'show_in_inbox')) {
        $schema = drupal_get_schema('node');
        db_add_field('node', 'show_in_inbox', $schema['fields']['show_in_inbox']);
    }
}

```

The new field will be added in your existing database on enabling this module.
> 2 votes

# Answer
If the field is static, I should think you want to create any db tables as part of the install (https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_install/7). Just don't forget to remove it as part of an uninstall.

If it's being created dynamically, then the point at which it needs to be created should dictate where and when to place the code.
> 0 votes

---
Tags: 7
---


# Question
Title: why not redirect to another page after form submit
I do this in my form submit

```
    $form_state['redirect']='checkout/' . $order->order_id;

```

but it not redirect to `checkout` page ( I test with another urls but it not work), I take screen shot after set `redirect` ,

also I get $from\_state by ref in function `function pre_register_node_form_submit($form, &$form_state) {` , **what do you think? where is the problem?**

another note is when I am use `drupal_goto` form not saved !!!, it redirect to my page with out anything saved.

Do you suggest me declare another submit function and add it to submit array of my content type and in it set `redirect`?

**Update**

also I test below

```
 if ($form_id == "pre_register_node_form") {
       $form['#submit'][] = 'mysite_submit_redirect';
}

function mysite_submit_redirect(&$form, &$form_state) {
  $form_state['redirect'] = 'home';
   // ym($form_state);

}

```

but not redirected :(

# Answer
If that's a node form, the problem is the node submit handler sets the redirect already in `node_form_submit`

If you want to redirect to checkout after a node form submit, you can do it by adding a submit handler to the `$form['actions']`:

```
/**
 * Implements hook_form_alter
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'NODE_TYPE_node_form') {
    $form['actions']['submit']['#submit'][] = 'MODULE_NODE_TYPE_submit';
  }
}

/**
 * NODE_TYPE submit handler
 */
function MODULE_NODE_TYPE_submit($form, &$form_state) {
  // You don't need order_id as /checkout will route to the correct location for user
  $form_state['redirect'] = 'checkout';
}

```

Note: You could also do it with Rules.
> 2 votes

---
Tags: forms
---


title: How to create a dynamic main menu tabs

text:
# Question
Title: How to create a dynamic main menu tabs
I want to create a dynamic main menu according to user roles. For example if an anonymous user visits he can only see the 'Home' and 'About Us' links, while registered users can see additional links like 'Contact Us'. Is there a way to do that, through a module perhaps? I don't want to edit in source code.

# Answer
You can use Menu per Role module.

Project page says:

> This module allows you to restrict access to menu items based on user roles. It depends on the Drupal core menu.module just activate both modules and edit a menu item as usual. There will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.
> 0 votes

---
Tags: routes
---


# Question
Title: How do i print image title in custom node for image gallery
I use content types for image gallery and write own custom node for image gallery all images are show in custom node by following code but i don't know how to print the image title.

In this code i have given static title 'Circles and Cycles ' and i need dynamically title of every image.

```
<div id="node-<?php print $node->nid; ?>" class="node-gallery">
<ul class="product-grid">

    <?php
        $imgcount = count($node->field_gallery_image['und']);
        for ($i = 0; $i < $imgcount; $i++) {
        $image_uri = $node->field_gallery_image['und'][$i]['uri'];
            // url
            $masthead_raw = image_style_url('gallery-thumb', $image_uri);

    ?>
      <li>
        <div class="main-product-wrapper">
          <a href="<?php print file_create_url($node->field_gallery_image['und'][$i]['uri']); ?>" rel="group-<?php print $node->nid; ?>" class="product-link">
       <div class="product-item"> <img class="image<?php print ($i + 1);?>" src="<?php print $masthead_raw; ?>" /></div></a>
          <div class="product-title"><a href="#">Circles and Cycles</a></div>

      </li>
      <?php
        }?>
    </ul>

  </div>

```

# Answer
> 0 votes
Create a `view` of your content type, then in this view select the `fields` as your content and then select the `title` and the `image`. then every image will have its own title. you can also theme it in any way that you want.

you need to output this `view` in your node page, so simply in your `template.php` and in `hook_preprocess_node` function suggest a theme hook for this content type (for example `page--node--gallery.tpl.php`) and then in the `page--node--gallery.tpl.php` output the view using `views_embed_view("view_name","display")`.

---
Tags: nodes, media
---


# Question
Title: Form validate & submit functions not firing on form loaded with AJAX
I've created a form that is loaded with ajax when clicking on a button, but the form validation doesn't work (and so is my custom submit function). The regular (Drupal's) form validation did work when I used `MENU_NORMAL_ITEM` and entered the form to a test page, but now when I'm using the current code it's not working.

* I guess that when I'll manage to "fix" Drupal's form validation I'll also be able to use my custom submit function.

My code:

```
function MYMODULE_menu() {
  $items['ajax/my_ajax_page'] = array(
      'title' => 'My title',
      'page callback' => 'MYMODULE_my_ajax_callback',
      'type' => MENU_CALLBACK,
      'access arguments' => array('access content'),
  );

  return $items;
}

function MYMODULE_my_ajax_callback() {
  print render(drupal_get_form('my_form'));
  drupal_exit();
}

```

Thanks.

# Answer
Well im not so sure about exiting...

i would try in my ajax callback:

```
function MYMODULE_my_ajax_callback() {
  $commands = array();
  $form = drupal_get_form('my_form');
  // im doing a replace command as an example, this could be another command invoked..
  $commands[] = ajax_command_replace('#container-to-append-form', render($form));

  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);
}

```
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: How to print preprocess_html variables in page.tpl
I have variable in template.php to use in different files like page.tpl, but written this in preprocess\_html function as below, how can i print this in page.tpl and html.tpl file.

```
mytheme_preprocess_html(&$variables){
      $variables['xyz'] = $xyz;
}

```

In page.tpl file, I tried with `print $xyz;` but it is not printing, where as I can able to print in html.tpl file this variable. Initially tried to add my code in preproces\_page function, but I can't able to get in html.tpl file in this case.

# Answer
> 3 votes
Yet another, perhaps simpler, to add variables to multiple templates, is too use an earlier `hook_preprocess`

> Preprocess theme variables for templates. This preprocess function is the first in the sequence of preprocessing and processing functions that is called when preparing variables for a template.

```
e.g:

/**
 * Implements hook_preprocess
 * @param $variables
 *   The variables array by reference.
 * @param $hook
 *   The name of the theme hook.
 */
function THEMENAME_preprocess(&$variables, $hook) {
  switch($hook){
    case 'html':
    case 'page':
      $variables['foo'] = 'my special variable';
    break;
  }
}

```

See also: `template_preprocess`

# Answer
> 1 votes
Variables added to template\_preprocess\_html are available in html.tpl.php `mytheme_preprocess_html(&$variables){
 $variables['xyz'] = $xyz;
}`

And variables added to template\_preprocess\_page are available in page.tpl.php `mytheme_preprocess_html(&$variables){
 $variables['xyz'] = $xyz;
}`

# Answer
> 0 votes
Not really a Drupal question, but

```
function MYTHEME_some_function() {
  return 'bar';
}

function MYTHEME_preprocess_html(&$vars) {
  $vars['foo'] = MYTHEME_some_function();
}

function MYTHEME_preprocess_page(&$vars) {
  $vars['foo'] = MYTHEME_some_function();
}

```

---
Tags: theming
---


title: Ban users from their IP

text:
# Question
Title: Ban users from their IP
I need to install a module that permit me (on my site) to ban IP. I have searched on Drupal.org and Google.com, but seems that there is not a good solution. All modules seems abandoned, so I ask here if someone use one of these modules and which one use. I don't want to start a thread about which is the best, only know which one I can use.

# Answer
> 5 votes
The built-in IP blocking (at /admin/config/people/ip-blocking) works just fine, but if you're looking for some slightly more advanced functionality, like blocking ranges of IPs, I've used IP Ranges with a great deal of success:

> IP Ranges is a module that let's you completely ban both single IP-addresses as well as full ranges from your site. The ban is triggered already at the early bootstrap phase, so you can get rid of unwanted visitors as early as possible without wasting server resources.
>
> You can also define whitelists that override blacklists, both single and ranged. The UI is similar to core ip-ban, so you will feel like home immediately.

# Answer
> 2 votes
In second the recommendation of the built-in IP blocking already metioned by Clive

If you want more features, the Anonymous Publishing module let you:

* let the administrator block abusers based on e-mail & IP address

What it does (beyond the basic module) is to let the admin block based upon observed abusive behaviour.

---
Tags: 7
---


# Question
Title: Save selected values from a checkbox into a field
I've the next form.

```
  $query = "SELECT name, tid FROM taxonomy_term_data WHERE vid=2 AND language = '$language_url';";
  $result = db_query($query);
  foreach ($result as $row2) {
     $options2[$row2->tid] = t($row2->name);
  }
  $form['group_config']['municipios'] = array(
     '#type' => 'checkboxes',
     '#title' => t('Municipios'),
     '#options' => $options2,
     '#required' => TRUE,
  );

```

I do a query to take the differents taxonomy terms that I have.

I don't know how to obtain the values that the user has selected and save into a field.

I've done the next code but It dosn't work.

```
   function anuncio_datos_usuario(&$form_state,$values){
        $node = new stdClass();
        $node->title = $values['titulo'];
    $node->type = $type;
    node_object_prepare($node);
    $node->language = $values['idioma'];
    $node->uid = $userid;
    $node->status = 0; //(1 or 0): published or not
    $node->promote = 0; //(1 or 0): promoted to front page
    $node->sticky = 0;
        if(count($values['municipios']))
        foreach($values['municipios'] as $municipio){
            if($municipio!=0){
                $node->field_municipio[LANGUAGE_NONE][]['tid']= $municipio;
            }

        }
    $node = node_submit($node); // Prepare node for saving
    node_save($node);

```

How can I save all the selected values into the field?

Thank you.

# Answer
> 0 votes
I think you what you want is an entity reference field.

Go the manage fields for your content type and create a new field of the type entity reference. In the setting for number of values choose unlimited and as widget choose checkboxes.

This will save the values for you, and display the chosen ones when the node is edited.

---
Tags: entities
---


# Question
Title: How to add class to specific TD in view table?
I have a view created /admin/structure/views and it is a table.

How do I add a class (f.ex. "bgred") for a specific TD (f.ex "title") in this table without using JavaScript ? I mean I have some hidden field (f.ex. "Status") and want to add class for field "Title" only when Status==1, is this possible ?

I want to add class to TD element not some div inside TD...

`<td class="bgred">`

# Answer
> 1 votes
```
1) click on desire field under 'Fields' in your view

2) select 'Style Settings'

3) check 'Customize field HTML' checkbox

4) check 'Create a CSS class' checkbox

5) enter 'replace-this-class' in 'CSS class' text field

```

then you should look into `hook_views_post_render` \- this where you can access the actual html output for each row. if you add a class to the field as described above, you will be able then do php find and replace based on any logic.

```
my_module_views_post_render(&$view, &$output, &$cache) {

    foreach ($view -> result as $result) {

        //not sure about that - you would need to debug that
        $result_status = $result -> status;

        //your php logic and new class assignment
        if($result_status == 1) {
            $class = 'new-class';
        }

        //what you want to replace - again double check that
        $replace = '<td class="replace-this-class';

        //alter `$output` variable
        $output = str_replace($replace, '<td class="'. $class .'"', $output);

    }

}

```

This is very ugly but it works. Of course you will need to look into the $output variable to make sure that you are targeting correct html.

---
Tags: views, theming
---


# Question
Title: How to programmatically select a view display in a view based on some node data
I have a content type that includes a field to store how that node should be displayed (display\_option). display\_option has two values (1|2).

I have created a view with two displays. Both are pages. Both use the path /node/% and use the node id as a contextual filter.

Display 1 has an additional filter criteria for requiring that display\_option = 1.

Display 2 has the same filter but with the criteria that display\_option = 2.

I can supply a node id to each display preview and they both individually produce the content I am looking for.

I was hoping Drupal would simply select the correct display based on the filter criteria but it doesn't. It always uses the display that is first in the view.

So I was looking at adding a pre-process function of some kind to template.php to manually change the view display id based on the node data.

I see quite a few views pre-processing functions and I am not sure which to use or at what point in the page build and view build process.

Any help would be appreciated including another method for accomplishing this.

# Answer
> 2 votes
The simple way to do this is

```
print $view views_get_view('yourviews_name','yourdisplayname');

```

for more information you can read documentation here

# Answer
> 2 votes
These options are not in order of relevance, just as they come to me.

## Option 1 - *hook\_menu*

As zhilevan suggests, you could simply use hook\_menu to define your own callback for node/% and return

```
views_get_view('yourviews_name','yourdisplayname');

```

from a conditional (if/switch) that checks 'display\_option' via `node_load(arg(1));`

If you do this you may have to fiddle with your module's weight in system table to make sure your path takes precedence over node.

*I am a little wary of this approach because the existing node/\* is such a useful callback and triggers all the node view hooks etc related to your content*

## Option 2 - *Page Manager*

You should be able to accomplish this with page manager (part of ctools)

If you took this option I expect that you might want to also use page manager existing pages module to override the node view page. There are some great tutorials for page manager if you need them.

## Option 3 - *Context*

Rather than display your view as pages, you could make render it as blocks and then use context to pick which block to put in your content region based on display\_option field. The node id argument could then be passed to views as a default argument 'Node from URL'.

To do this you would also need context\_entity\_field so that you can use node fields as conditions in contexts.

*This option means that you don't have to actually override the core node path (node/\*), which seems a lighter touch*

## Option 4 - *Display Suite*

Display suite allows you to create custom view modes for your nodes. You can also allow node authors to pick a display for individual nodes (I really like display suite, and I tend to use it a lot).

You could then set up the different view modes to contain the view of your choice, either by adding views\_get\_view() call in you theme (see option 1), or by using a display suite 'dynamic field' to add the two different views as fields to your node, and show only one in each view mode.

This way you do not need your field 'display\_options', as the selection is already handled by ds. If you did not want to give node authors a full choice of view modes, you could try contextual view modes, and make the selection of view mode from your existing field (via context\_entity\_field)

## Option 5 - *View field*

You could present a restricted choice of views in the node edit form to add to the node as a additional field. The options could be the two page views you have created. This would require View field.

# Answer
> 2 votes
For similar use-case I used

```
hook_views_pre_view(&$view, &$display_id, &$args)

```

then do the logic and simply

```
$view->set_display('name_of_your_display');

```

---
Tags: 7, views
---


# Question
Title: Possible to manage display of Profile2 profile fieldset on user registration
Using profile2 module I have set my Student profile to "Show during user account registration". This shows the fields I have created for the profile2 Student profile in a fieldset inside the user registration form. I am now struggling to gain any control over the display of my profile2 Student profile fields on the registration form. It is possible to manage the display of a profile2 profile displayed on the user registration form through display suite or another method, or is the only option using hook\_form\_alter.

Thanks

# Answer
It's a while since I used panels for this, but I'm quite sure you can use panels, and enable the panels page for the user/%user/edit page. Then create a new variant for this page and rearrange the elements through the content section as you would for a front-end panel. If you're not already using panels for other aspects of your site, you may want to try Display Suite, which I've never tried out. Choose the one that works best for your needs and stick with it to avoid module bloat.
> 0 votes

---
Tags: display-suite, users
---


# Question
Title: How do I save the values for a custom fieldset?
Relating to my question (here). I made a custom field set to toggle organic group visibility. The UI looks and functions as it should, meaning when I have both my fieldset and `$form['group_access']` fieldset showing, I can toggle settings from either and the changes show correctly in both. When I hide `$form['group_access']` with `$form['group_access']['#access']=FALSE;` the values do not appear to get written to the database when I hit save. Shouldn't I be able to set `$form['group_access']['und']['#entity']->group_access['und'][0]['value']` to the values in my custom fieldset? Any ideas? Thanks

# Answer
One way to do it would be in `hook_form_alter` add a custom validate handler:

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

```

then you should be able to do (double check that with debug(), print\_r() or devel):

```
function my_custom_validate_handler(&$form, &$form_state) {

    $form_state['values']['group_access']['und'][0]['value'] = 1;

}

```

Another way would be to set a '#default\_value' and it should be something like that:

```
$form['group_access']['und'][0]['default']['#default_value'] = 1

```

Hope that helps!
> 0 votes

---
Tags: forms, organic-groups
---


# Question
Title: Views Filter 2 Content types but with condition on one of them
I looked up this one before posting: Views filter criteria multiple content types (Drupal 7)

And even though the problem is the same, the solutions provided do not seem to work.

I have Content Types A and B. B has a boolean field.

I need to filter and display all As and Bs if boolean is true.

My filter setup looks like this:

Content : Published AND Content Type : A

OR

Content : Published AND Content Type : B AND Boolean Field : True

The Query that gets produced is the following:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM `node`
INNER JOIN `field_data_field_boolean` ON node.nid = field_data_field_boolean.entity_id
  AND (field_data_field_boolean.entity_type = 'node'
  AND field_data_field_boolean.deleted = '0')
WHERE (( (node.status = '1')
  AND (node.type IN  ('poll')) )OR( (node.status = '1') AND (node.type IN  ('webform'))
  AND (field_data_field_boolean.field_boolean_value = '1') ))
ORDER BY node_created DESC

```

The problem is that Inner Join that gets produced instead of a Left Join for instance.

Which setup would allow me to perform the required filtering?

EDIT: Seems it's a know bug. Related links: http://drupal.org/node/1766338 Changing an inner join to a left join in views 3.3?

# Answer
> 7 votes
Although this post is quite old, it appears it's still an issue going up to Views 7.x-3.7. Referring to the post already mentioned here and specifically comment 36 on that page, I found my working solution.

I had two content types that I wanted to show the title from: an Event and a Blog, however I only wanted the blog posts which had a Boolean field returning as true. Below is a screenshot of what my grouping filters look like but the trick is, on the Boolean filter, **make sure you select the 'Reduce duplicates' check-box**. Once I did that, I got the results I was expecting.

Hope that helps.

# Answer
> 0 votes
I often struggle with views doing what I want. My solution is to override the automatically generated query with my own.

Below I give you an example of a list of members of the currently viewed group with the specific group role:

```
function mymodule_views_pre_execute(&$view) {
    if($view->name=="og_members") {
        $nid = arg(1);
        $gid = mymodule_get_gid_from_nid($nid);
        $query = db_select('users');
        $query->join('og_users_roles', 'roles', 'users.uid = roles.uid');
        $query->addfield('users','name','users_name');
        $query->addfield('users','uid','uid');
        $query->condition('roles.rid', VISITOR_ROLE_ID,'!=');
        $query->condition('roles.gid', $gid,'=');
        $view->build_info['query'] = $query;
    }
}

```

A thing to not here is that returned field should match the fields that the view will expect.

---
Tags: 7, views
---


# Question
Title: Views filter criteria multiple content types (Drupal 7)
I have created a view and added the filter criteria content type. I have chosen two content types. They are both being displayed. I would like then further filter one of the content types so that only those which have had a check box selected will display. Is it possible to do this in views?

Thanks, JP

# Answer
This can be done by modifying the Views filter criteria.
> 4 votes

# Answer
Under Filter Criteria you probably added:

Content Type A
Content type B

Now you can extend this by adding:

Content Type A check-box (is one of: yes or whatever)
Content Type B check-box (is one of: yes or whatever)

Then under Filter Criteria instead of add, click on the arrow and choose "And/Or, Rearrange".

Choose your operator and move the respective fields together.

Then it will look something like this:

> Content Type A
> AND
> Content Type A check-box
>
> OR
>
> Content Type B
> AND
> Content Type B check-box
> 1 votes

# Answer
When you expose a filter you can select the option "Limit on selected" or something like this, that force the exposed filter to show only selected filter.
> 0 votes

# Answer
I had the exact same issue and I've posted an answer to this with a screenshot at Views Filter 2 Content types but with condition on one of them. Please vote it up if it helps you. Thanks.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Using Date Popup widget with custom format Date field
I need to save a date in a very specific format: (`2013-03-09\T17:01:34.1\Z` to be precise).

I also need to allow users to edit this date after it's been saved.

I want to use the Date Popup submodule of Date to allow users to enter dates. However, it doesn't seem to support custom formats. When I enable Date Popup, I see that I lose seconds granularity, and I can no longer use custom formats at all.

Is there a way to use custom formats with Date Popup? If not, is there a recommended way of adding a popup calendar to my date field in a way that will generate dates in my custom format? Does anyone know why the developer of Date made Date Popup incompatible with custom formats?

# Answer
> 2 votes
As noted in another comment, you should set "#date\_format". You should however not set it in hook\_form\_alter(), but rather in hook\_date\_combo\_process\_alter(). Ie:

```
/**
 * Implements hook_date_combo_process_alter().
 *
 * Force 'd.m.Y' date format
 */
function mymodule_date_combo_process_alter(&$element, &$form_state, $context) {
  $element['value']['#date_format'] = 'd.m.Y';
}

```

The popup sub-module uses the value set here, but not as-is. The thing is that the date format used by the jquery popup is different than that set in #date\_format. The date\_popup sub-module automatically converts the date format with the functions "date\_popup\_format\_to\_popup" and "date\_popup\_format\_to\_popup\_time".

Sorry that I didn't answer your question completely. I don't have time right now to do that. But I hope you can get I gave you some insight that will help you for your specific problem. You may want to examine the functions 'date\_popup\_process\_date\_part' and 'date\_popup\_process\_time\_part' in the file 'date\_popup/date\_popup.module'

# Answer
> 2 votes
Drupal's Date module includes a 'Date Popup' sub-module which handles date pop-up widgets. These widgets are available in the FAPI (form api) and can be configured with custom formats via the `#date_format` property.

You could implement `hook_form_alter()` and change the `#date_format` property on the date field you're working with. I believe this property will support all formatting available in PHP's standard date() function.

# Answer
> 0 votes
If you are referring to the Scheduler block options that have to be changed site-wide, the format can be set on the Scheduler settings page (http://example.com/admin/settings/scheduler)

---
Tags: datetime
---


# Question
Title: How do i give other users permissions for modules?
I have the following question: How do I give other users permissions for modules?
Example: FAQ module.

Any and all help greatly appreciated.

# Answer
To adminster the permissions for a module navigate to *Administration » People » Permissions*. There you will find a panel where you can assign permissions for the various modules. The section for the FAQ (Frequently Asked Questions) module is shown below:

As you can see, this module have three separate permissions:

* Administer FAQ module
* Administer FAQ order
* View FAQ pages

To grant as specific role a permission, you tick the mark to the right of the permission and below the role.

In the screen shot above, all roles are granted the right to "View FAQ pages", but only the administrator is granted the other two permissions.
> 1 votes

---
Tags: users
---


# Question
Title: Importing CSV file to Generate Orders in Drupal Commerce
I am using drupal commerce kickstart. I need to generate order-ids with dummy billing and shipping information. How to import csv file with order particulars? Is there any module? How to proceed?

# Answer
You can do this with the migrate module: https://drupal.org/project/migrate and the add-on module commerce migrate: https://drupal.org/project/commerce\_migrate .

This is a coding solution, but I can't think of any other way you could do this without some coding of your own.
> 2 votes

---
Tags: commerce
---