# Question
Title: Drupal 7: how to redesign, move stuff around, for a content type page?
If when creating a View, I create a list of a specific content type, let's say Staff. It lists everyone from the Staff content type. I have this setting too: Link to the original piece of content. Then I get a list of content type labels and content type data. How can I rearrange everything? How can I edit the HTML?

I don't want to create a view for a specific content type, I want to redesign (edit HTML) the content type page, example: domain.com/node/5

# Answer
Not clear with your questions ,adding some pointers on some assumptions.

Custom Way

1 . If you want to override a node structure for a specific content type

-- You can copy the node.tpl.php to your theme and rename it to node--type.tpl.php. Inside node--type.tpl.php , you will be rearranging the elements.

2 . If you want to override every node,irrespective to any content type.

-- Copy node.tpl.php inside your theme and do the rearrangement of elements.

3 . If you want to override a particular node

-- Copy the node.tpl.php and rename it to node--nodeid.tpl.php and do the rearrangement of elements

Some Helpful Links:

https://drupal.org/node/1089656

http://www.youtube.com/watch?v=dfwU0WtCuPs

**Remember** to clear the caches after you are done with building of templates.

Using Contrib Module

You can use panels module to override node templates without creating them. panele module will do that for you.

Some Helpful Links:

http://www.youtube.com/watch?v=\_VIkE2ZS5oU
> 1 votes

---
Tags: views, nodes
---


title: Affect a theme to a view page

text:
# Question
Title: Affect a theme to a view page
So, I create a view page that list the webform results, and I want to affect the administration theme to this page, How ?

Thank you.

# Answer
Check admin\_theme module. This will allow you to set custom pages in admin theme.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Webform component weight within a Fieldset
I am creating a settings page for a specific Webform in version 6.x-3.x which finds all select option components in the form and creates a numeric textfield setting correlating to each select option. The Select Options are in fieldsets. On the settings page, I want the numeric textfields to show up in the same order that the select options show up in the form.

db\_querying the right select options in the `webform_component` table is working fine, but the select options show up out of order when ordering by `weight`.

For example:

The Webform

```
Fieldset 1
- Textfield 1
- Select Option 1
- Select Option 2
Fieldset 2
- Select Option 3
- Select Option 4

```

`db_query('SELECT * FROM drupal_webform_component WHERE TYPE = "select" AND nid=123 ORDER BY weight');` generates results like this:

```
Select Option 1
Select Option 3
Select Option 4
Select Option 2

```

How do I order Webform results of components within fieldsets to reflect the order they appear on the form? What would the db\_query look like?

# Answer
Ok, there is a column `pid` in `webform_components` for individual components. This value correlates with the `cid` of the fieldset. A `LEFT OUTER JOIN` between the `cid` and `pid` columns, filtered by the webform node id - `nid`, then ordered by the fieldset `weight` followed by the select option `weight` returns the components in the correct order as they appear on the node form. Here is the db\_query statement.

```
db_query('SELECT *
FROM webform_component AS f
LEFT OUTER JOIN webform_component AS s ON f.cid = s.pid
WHERE f.nid = 123 AND s.nid = 123 AND f.type = "fieldset" AND s.type = "select"
ORDER BY f.weight, s.weight');

```

This works. Any advice on optimizing this query is appreciated.
> 0 votes

---
Tags: 6, webforms, database
---


# Question
Title: Trouble incorporating "Related Articles" block into panel
I have a "Related Articles" view block that is in use on the site, and it functions fine. The site's original dev team configured everything through templates, but the code is placed in the "Article" template properly, and it all is well. This is a standard Related Articles block that uses the contextual filter "Content: Has taxonomy term ID" to find other nodes of Article type with the same taxonomy terms.

I have a problem, though, creating a similar block for a recently created content type ("News"). This node type's display is configured through Panels, though I'm not sure if that's what's causing the issue. I cloned the original block and altered the (non-contextual) filter to select content based on whether the content type is either Article or News (the original does only Article). Everything else is the same, including the contextual filters. When I place this block in the News panel, I get no results in the block (I've double-checked to make sure I'm using terms that exist on other articles).

I'm sure there are a number of things that could be causing the issue, but I don't know where to look. Can you offer me any guidance?

Thank you.

EDIT:

Here is their php code. I'm not proficient in php, but this looks pretty barebones to me.

```
<?php print '<div class="contextual-links-region panel-pane pane-views pane-slideshow-displays contextual-links-region fusion-block-title-gray-text-red clear"><h2 class="pane-title block-title">Related Stories</h2><div class="pane-content content">' . views_embed_view('related_stories', 'block') . '</div></div>'; ?>

```

EDIT 2:

I have tried placing the following php into the panel:

```
<?php
$node = menu_get_object();
if (is_object($node)) {
  $tid = $node->field_article_tags['und'][0]['value'];
  $output = views_embed_view('related_articles_for_news_', 'block', $tid);
}
echo $output;
?>

```

Still no luck. Everything looks correct to me. The URL on the view as I edit it is:

admin/structure/views/view/related\_articles\_for\_news\_/edit

and this is the only display in the View. The advanced settings say that the machine name is "block", and I confirmed that field\_article\_tags is correct.

Additionally, I accidentally left off the trailing underscore in the view title originally, and, of course, that did not work either.

Any thoughts as to where I might be going wrong?

Thanks again.

# Answer
> 0 votes
The problem is that, your view accepts a Term ID which it uses to get other nodes tagged with the same term. But when you are placing the views block (accepting TID asparameter) in Panels, how are you passing the context to it?

This is probably why your dev went in for the code based approach. I think you can create a custom PHP panels content, grab the node from the present path, then grab the tid from term reference field, and the pass in the tid as context while calling the view through views\_embed\_view() function.

If you want you can paste the code your dev used and I can help you how you can re use the code in panels to get the same result.

Code Should be something like this:

```
$node = menu_get_object();
if (is_object($node)) {
  $tid = $node->field_yourfieldname['und'][0]['value'];
  $output = views_embed_view('your view name', 'display name', $tid);
}
echo $output;

```

Put the above code in the panel, using a custom content with PHP.

---
Tags: blocks, panels, views
---


# Question
Title: How to save the previously selected option in the selection box, the default value strays
Please help to understand what the problem is. I created a field Select to list in the comments to type of material field values I needed my, I redefined options list in the Custom Module

```
$query = db_select('node', 'n')
        ->fields('n', array('type', 'uid', 'title', 'nid'))
        ->condition('n.type', 'brigada_type', '=');
     $result = $query->execute();
     $brigade_list = array();
        foreach($result as $value){
             $brigade_list[$value->nid] = $value->title;
        }
        $form['field_select_brigade']['und']['#options'] = array(0 => t('- Select -')) + $brigade_list;

```

After I select a value from the list and create a comment I check it, and then only published but during the inspection the default value strays.

before

after

# Answer
> 1 votes
Solved the problem yourself with the help of code. It was necessary to create a handler instead comment\_form\_submit and create in him the values of a variable\_set of my field value, so, I create custom field.

```
    function comment_author_form_comment_form_alter(&$form, &$form_state, $form_id){
           if($form_id == 'comment_node_zayavka_form'){
             $query = db_select('node', 'n')
                ->fields('n', array('type', 'uid', 'title', 'nid'))
                ->condition('n.type', 'brigada_type', '=');
             $result = $query->execute();
             $brigade_list = array();
                foreach($result as $value){
                    //if($value->uid == $user->uid){
                     $brigade_list[] = $value->title;
                    //}
                }
                $form['field_select_brigade_1'] = array(
                    '#type' => 'select',
                    '#title' => t('Select brigade'),
                    '#options' => $brigade_list,
                    '#description' => t('Please select the team that was sent to you with reference to this application.'),
                    '#required' => TRUE,
                    '#default_value' => variable_get('comment_field_brigade_selection'),
                );
        $form['#submit'] = array('comment_author_comment_form_submit');
        }
function comment_author_comment_form_submit($form, &$form_state){
        if(isset($form_state['values']['field_select_brigade_1'])){
              variable_set('comment_field_brigade_selection', $form_state['values']['field_select_brigade_1']);
            }
        }

```

# Answer
> 0 votes
You also need to assign a `#default_value` on your `select` form element in order to have the preselected option.

```
$form['field_select_brigade']['und']['#default_value'] =  $brigade_list[$preselected_key];

```

---
Tags: entities, comments
---


title: How to add a top nav bar?

text:
# Question
Title: How to add a top nav bar?
I would like to add a Facebook style or StackExchange style top navbar to my site. It should show the username, mini profile pix, userpoints, search box and a few other links.

Is there a module for that?

# Answer
I don't find any module does that specific purpose of making top bar. It is usually done by custom themeing. Basically, you add a new region to your theme. For example, You define a new region called "topnav" in .info; code the markup in template.php and .css files. Then go to block administration page, assign stuffs to the topnav region.
> 2 votes

# Answer
I have also wanted to do this, I have edited the "mix and match" theme but this should work on any theme in theory.

edit the **page.tpl.php**

add the following code at top of page

```
<head>
<style type="text/css">
#userbar {text-align:right; margin-right:auto; margin-left:auto;}
</style>
<?php global $user;
$uid = $user->uid;
$points = userpoints_get_current_points($uid);
?>
</head>

```

this makes your links right aligned and declares $points for the user logged in.

to add the content you also add the following (position this on the page where you want your bar to appear, ie in the header).

```
<?php if ($user->uid): ?>
<div id="userbar"><a href="user"><?php print $user->name; ?></a> Points: <?php print $points; ?></div>
<?php endif; ?>

```

you can also add other things to your bar as required :)
> 1 votes

# Answer
There is a great Nav Bar module called Mobile Friendly Navigation Toolbar:

> A very simple mobile friendly navigation toolbar introduced as part of the Spark project to solve mobile editing problems with the Drupal 7 shipped toolbar, that is not very friendly to small screen sizes.

This module is only for Drupal 7, though.
> 0 votes

---
Tags: 7, navigation
---


title: View mode for specific bundle

text:
# Question
Title: View mode for specific bundle
Drupal 7 makes it quite easy to create a new view mode (see this tutorial for instance), but is there a way to define a view mode that is only available for a specific bundle (content type)?

# Answer
> 13 votes
No.

View modes are specified per entity type, not bundle, as hook\_entity\_info() shows.

It is also not possible to define extra fields which are only available for a specific bundle/view mode combination, only per bundle.

# Answer
> 1 votes
The Drupal contrib module Entity View Mode lets you create view modes and specify for which specific bundles: Article, Basic page, etc.

---
Tags: 7, entities
---


# Question
Title: What to use for node_prepare in Drupal 7
I am converting a module from Drupal 6 to Drupal 7. I have come across a Drupal 6 functional call named node\_prepare and I am not sure what needs to be done to make this work with Drupal 7. What should this function be replaced with?

Thanks.

# Answer
You don't need to replace it with anything as it happens, you can just remove it.

All that function does is prepare the node body for display. Since the body is a field in Drupal 7, all that processing is done elsewhere, and it's not something you need to invoke manually any more.
> 1 votes

---
Tags: 7
---


# Question
Title: How to include "children" content types on a content type page?
Let's say I override the way a content type page looks. My content type is Parent. So I create a page named: node--parent.tpl.php

But how about when you want to use nested content types?

Let's say:

* Content Type Parent
* Content Type Child

I use node--parent.tpl.php, but how do I display the children that belong to the parent? (linked using **Contextual Filters**).

For example in node--parent.tpl.php have a way to display:

Parent Name: Joe

Children: Sue, Phil, Mary and Jim

# Answer
> 3 votes
Contextual filters are part of Views, they can't be used to link content types together. If you're simulating a relationship between the two types using a contextual filter, it will only exist in the very narrow context of that View.

The standard way to link content types together is with the Entity Reference module. Something similar to the following should get you what you're looking for:

* Add a multiple cardinality entity reference field to the Parent content type, referencing the Child type.
* Optionally install Inline Entity Form, if creating the Child content while inside the Parent edit form makes sense for your use case. It provides a widget for the entity reference field type. I won't go into details, if you choose that widget and visit the edit form for a Parent node, you'll see what it does.
* Use either the autocomplete or inline entity widget to relate the Child nodes to the relevant Parent nodes.
* Visit the display options for the Parent content type, choose "Rendered Entity" for the display format of your entity reference field, and in the settings choose an appropriate view mode.

That will render the Child nodes inside the Parent node without the need to alter the template file at all.

---
Tags: views, nodes
---


# Question
Title: How to push changes from a dev environment to prod
Our team of 10 developers would like to use Dev, Test, Staging and Production environments for our large site. **How can we streamline pushing our changes from one site to another**, keeping them as identical as possible?

The difference between this question and How to migrate from test environment to production environment? is that we would like to push changes automatically/regularly so that the environments not very different.

We have been using a Dev and Production environment for the past few years, and each environment has its own SVN code repo. The Features module has been used in a few places, but it does not work with Blocks or Content.

One proposal was to use Drush and use archive-dump and archive-restore to push the changes between the environments, but Production has content provided by visitors and users and pushing to Production would wipe out that content.

Has anybody answered this question before?

# Answer
I use a custom script to automatically pull production to backup and update servers (an update server is a sanitized clone of production with updates applied via pm-update, standing by and ready for testing). You might get some ideas looking at that. However, I'd say that it would be a bad idea to *automatically* sync either prod to dev, or dev to prod. Only publish to production after a human has tested and validated the release you'd like to bring live. As for automating prod to dev updates, I'd think that the devs would find that very annoying.

One thing that you could pretty easily do is automate the updates of your staging server. Just pull the database down from production, pull the latest code up from the dev branch of your repository, and run updatedb and your test suite. A human could then validate the results and publish the code to production if it was ready.
> 3 votes

# Answer
Use Features, Context & Boxes for Blocks functionality, along with Deploy and UUID for content.

Whenever possible, use code, CTools exportables, and update hooks in custom modules.
> 2 votes

# Answer
I was researching something similar just the other day -- except that it was an automatic way to periodically pull down the most recent code from the remote repo to your local dev environment. IIRC it involved a couple of `drush` scripts. Give me a minute and I know can find it again.
> 0 votes

# Answer
Pantheon (https://www.getpantheon.com/) does a great job to manage this workflow. I used to handle this myself with git + features + scripts, but it was more trouble than it was worth. I started using Pantheon and made my life so much easier. I personally would rather spend my time building websites rather than worrying about workflows, servers, etc. But it only has 3 environments - dev, test and live, so it may not work for you if you have to have 4 environments. They have a free tier so you can give it a whirl.
> 0 votes

---
Tags: 7, drush, version-control, staging
---


# Question
Title: See what path aliases are set up with Drush?
Ive installed Drush and my local system is a Mac. It seems to have worked as when I type `drush` into the terminal a long list of commands comes up.

When I type `drush cc all` I get the message `'drush' cache was cleared` . Does that mean my path aliases are set up? Or could I be getting a false success message? I have a number of Drupal sites locally and I dont know which (if any) is having its cache cleared.

# Answer
> 2 votes
You have to either be within a drupal doc\_root (aka apache verbiage) or have properly configured drush site aliases for commands to work:

Eg, if your site lives at /var/www/

```
cd /var/www/
drush cc all

```

Or if you have setup a drush site alias of @local, then from anywhere on your system:

```
drush @local cc all

```

# Answer
> 2 votes
To answer what in the title of the question is asked:

```
drush site-alias

```

lists all site aliases you have defined.

---
Tags: drush
---


# Question
Title: Display the value of a field list in views
suppose we have this field list:

```
Status
  1 => foo
  2 => bar
  3 => foo_bar

```

in the views page I want to display

```
Status
------
foo
bar
foo_bar

```

but now it give me:

```
Status
------
1
2
3

```

# Answer
> 1 votes
In your view, click on the field, under Formatter select 'Default'.

---
Tags: views
---


# Question
Title: How to create features for site configuration in drupal 7
I have one requirement where all admin configuration need to be converted in to features eg caching must be enable

# Answer
> 2 votes
Strongram module will allow to export system configurations and settings through features.

# Answer
> 2 votes
There is also Configuration Management module, which is under active development and tries to implement Drupal 8 way of configuration management in Drupal 7. It is worth to take a look.

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

---
Tags: 7, features
---


title: How to theme a block with product list

text:
# Question
Title: How to theme a block with product list
I'm trying to create a template for a block that I created at Views. So this View (block) has some filters in it, and if I use the default template layout lists my products as it should. My problem is that when I use a custom template, I don't know how to access to those products variables inside that block. I tried to find that variable using get\_defined\_vars() but was impossible because it display a huge list of vars, and yes, products are there, in an array called 'rendered\_content', but I can't figure out the path to that variable in the huge list that is printed.

Please, help this desperate soul.

# Answer
use devel module for better debugging option.Devel module provides dpm() which will make the array structure easy to see.When you know the exact array key where your content lies, its better to check the output with that key instead of dumping the complete vars.

so better you first do `dpm(get_defined_vars());`after installing devel module it will return the same what you are seeing now but in a well structure way, when you figure out the next better key of output holding the data,use dpm() on the returned array with useful key
> 0 votes

---
Tags: theming, commerce
---


title: How to create a profile page?

text:
# Question
Title: How to create a profile page?
I'd like to create a profile page (visible for every visitor) for every user on my website. There should be displayed some personal information about the user (name, date of birth, bio...) and some things related to their activity on the website (favorite articles, own articles...).

I've already added a lot of fields to users (wich have to be filled in during the registration) in the **People \> Account settings \> Manage fields** section and created some views with the Views module in order to display their favorites etc.

I'm struggling with the next step. I'm not sure whether I should create a profile page myself or use the Profile2 module (wich is installed at the moment). First of all, I don't know how I can create a profile page myself. How can I set this up, assign it to a user...? Secondly, I'm not very convinced by the power of Profiles2: I managed to add fields to a user's profile page, but I can't find a way to add blocks or views to it. A nice feature is the 'private' field option, but I'm wondering if that can't be realised without the module.

Can you help me in finding a good solution?

# Answer
You can consider using Panels module to override the user page.

UPDATE:

You must be knowing default user page has path of form 'user/\[uid\]'. Now to replace that with our new panels page, visit this link: "admin/structure/pages".

There, you can enable "user\_view".

Now when you edit that, you choose layout and content (add the fields). Then when you visit user page at user/\[uid\], the new layout will take effect.
> 2 votes

# Answer
* Create a profile using profile2 module

http://www.youtube.com/watch?v=jPbazpRCwP0
* Do you need it here

I do not think so, what profile 2 module does is it separates user entity with a separate profile entity.Lets consider this with an example you have user on site with name,age fields but the user can have multiple profiles on the basis of Sports, Music so fields on the profile goes in that way. You may have fields like compositions,favourites on music profile for the user and games.. etc. fields on sports profile for the user but name and age will be on the user entity as it is common to both profiles With fields you have mentioned you do not need profile2 module instead panels module will be good for you as neo has suggested before.
* Make profile private without profile2 module

Again panels will make it doable.

https://insready.com/en/blog/3-lines-code-panels3-and-profile-modules-create-user-configurable-privacy-settings
* User recent activity

To display the summary of user's recent activity, you can setup a view with a contextual filter of user id, set 'Content pane' display type for your view, and add it to user panel page.
> 1 votes

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


title: Prevent File Upload during an ajax call

text:
# Question
Title: Prevent File Upload during an ajax call
I have a form that includes a managed\_file field as well as a data popup and select field. When the user selects a date, an ajax call is made to populate the select field. However, I noticed that each time the ajax call is made, the file is uploaded, causing multiple copies of the file to to exist (each subsequent file having a number appended to the . If the user selects another date, the file is uploaded again. How do I prevent the file from being uploaded multiple times during the ajax call?

Here is my form code

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

  $form['file_fid'] = array(
    '#type' => 'managed_file',
    '#title' => 'Import File',
    '#size' => 100,
    '#description' => 'Select an import file.',
      '#upload_location' => 'private://filelocation/',
      '#required' => true,
      '#default_value' => variable_get('file_fid',''),
    );
    $form['date'] = array(
      '#type' => 'date_popup',
      '#date_format' => 'm/d/Y',
      '#title' => 'Start Date',
      '#description' => 'Enter the start date of the meet. After changing the date, select the meet below',
      '#ajax' => array(
      'event' => 'change',
      'callback' => '_timesdb_import_meets_ajax',
      'wrapper' => 'timesdb-import-meets',
    ),
  );

  $meet_options = isset($form_state['values']['date']) ? _timesdb_import_get_meets($form_state['values']['date']) : array();
  $form['meet'] = array(
    '#type' => 'select',
    '#title' => 'Select meet',
    '#options' => $meet_options,
    '#prefix' => '<div id="timesdb-import-meets">',
    '#suffix' => '</div>',
  );

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

```

The ajax callback looks like this

```
function _timesdb_import_meets_ajax($form,&$form_state) {
  return $form['meet'];
}

```

# Answer
> 0 votes
I ended up returning the entire form. I moved the prefix and suffix to the form element, so the entire form is replaced after the ajax call. I figured, if I can't beat it, join it :).

```
$form = array(
    '#prefix' => '<div id="timesdb-import-meets">',
    '#suffix' => '</div>',
);
$form['file_fid'] = array(
    //'#name' => 'files[importfile]',
    '#type' => 'managed_file',
    '#title' => 'Import File',
    '#size' => 100,
    '#description' => 'Select an import file.  Supported types are CSV from SWIMS or Commlink',
    '#upload_location' => 'private://timesdatabase/',
    '#required' => true,
    '#default_value' => variable_get('file_fid',''),
);

$form['date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#title' => 'Start Date',
    '#description' => 'Enter the start date of the meet. After changing the date, select the meet below',
    '#ajax' => array(
            'event' => 'change',
            'callback' => '_timesdb_import_meets_ajax',
            'wrapper' => 'timesdb-import-meets',
        ),

);
$meet_options = isset($form_state['values']['date']) ? _timesdb_import_get_meets($form_state['values']['date']) : array();
$form['meet'] = array(
    '#type' => 'select',
    '#title' => 'Select meet',
    '#options' => $meet_options,

);

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

```

# Answer
> 0 votes
Drupal submits the entire form at every ajax call, I think you'd have to use hooks before submit, before send or similar to prevent it. Heres something to get you started. Or simply put the file field last or at least after the ajax form elements.

Disable all form elements when doing AJAX

Ideally drupal should allow you to specify what you want to submit. please share your solution if you figure it out.

---
Tags: 7, forms, ajax, files
---


# Question
Title: How to display instances of a field (field collection) in tabs?
I have a content type with a field which has a number of instances (actually, it's a Field Collection with a vimeo embed and a text field). I would like to have each instance of the field to be shown as a tab? Field Group seems like a natural candidate for this role, but from what i understand it enables me only to build tabs for particular fields, not fields instances.

The way I'd dream this functionality to be is:
1) I add another field to my field collection named, say, "Tab title"
2) In "manage display" of the node I set the display of the field to be of "tabbed instance" type.
3) In settings of this display I set the title of the tab to be the new field introduced in 1) by Token.
Of course, any other way of acieving the goal would be also most welcome.
Is there a simple way to obtain such a functionality?

# Answer
> 1 votes
Someone up there likes you...

Field Collection Tab formatter

> Field collection tabs provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.
>
> **Features**
>
> You can optionally choose a field from the field collection item to be used as the tab title.

It's uncannily close to what you're asking for. Your question might as well have been the user story that inspired that module :)

---
Tags: entities, routes
---


title: Ctools modals without AJAX

text:
# Question
Title: Ctools modals without AJAX
What's the sanest way to present a Ctools modal to the user while bypassing the normal AJAX workflow? For example, how could I show a completely JavaScript-generated "Are you sure you want to log out?" confirmation prompt to the user in a Ctools modal after the user clicks the "log out" link?

I know I can probably fake a box which would get the same styling as the Ctools modal, but I'd rather avoid silly hacks if not strictly necessary.

# Answer
> 8 votes
This should be possible by invoking `Drupal.CTools.Modal.show` directly. The function takes one argument (the modal-style), which either can be a string pointing to an object on `Drupal.settings` or the style-object itself.

After showing the dialog, it is possible to populate title and content using jQuery:

```
Drupal.CTools.Modal.show('my-modal-style');
$('#modal-title').html('my-title');
$('#modal-content').html('some markup here').scrollTop(0);
Drupal.attachBehaviors();

```

In your PHP code, you need to ensure that ctools `modal.js` and also `misc/ajax.js` gets loaded:

```
drupal_add_js('misc/ajax.js');

ctools_add_js('modal');
ctools_add_css('modal');

// Add your modal style to the settings. You find the defaults in modal.js near the top:
drupal_add_js(array(
  'my-modal-style' => array(
    'modalSize' => array(
      'type' => 'fixed',
      'width' => 250,
      'height' => 250,
    ),
    'closeText' => 'Dismiss',
    'closeImage' => ...
  ),
), 'setting');

```

---
Tags: 7, chaos-tool-suite, javascript
---


title: Token for Field Collection values

text:
# Question
Title: Token for Field Collection values
I have a node that has a field created with Field Collection module. Field is composed of 3 subfields: dropdown list and 2 text boxes.

I want to get values from those 3 fields in my Rule.

How would I reference those fields?

I have installed Advanced Entity Tokens module.

thx!

# Answer
Solved! There is a list of all available tokens in: admin/help/token.

In my case I needed to get 3 field values from Field Collection:

```
[node:field-school-undergrad:0:field-school-list]
[node:field-school-undergrad:0:field-school-degree]
[node:field-school-undergrad:0:field-school-year]

```
> 3 votes

---
Tags: tokens, entities
---


title: Redirect incoming traffic to homepage

text:
# Question
Title: Redirect incoming traffic to homepage
How can I set Drupal 7 so that all incoming traffic is redirected to the homepage? I need to ensure all visitors go to the homepage, even if they click a link on some other site that links to example.com/section/node-1

# Answer
You could do this easier in your .htaccess file:

```
RewriteEngine on
RewriteCond %{REQUEST_URI} !/$
RewriteRule $ / [R=302,L]

```

Put this at the bottom of your .htaccess file and you're set.
> 1 votes

# Answer
You could do something like this:

```
function yourmodule_init() {
  $destination = drupal_get_destination();
  if ($destination['destination'] != variable_get('site_frontpage', 'url-home')) {
    drupal_goto('<front>');
  }
}

```

And you Can add to th if statement your custom conditions

Hope this helps
> 0 votes

# Answer
Here are rewrite conditions to redirect all incoming traffic (from another domain) to the homepage. Put this in the `.htaccess` file.

Don't forget to update the URL with your correct website domain.

```
RewriteCond %{HTTP_REFERER} .
RewriteCond %{HTTP_REFERER} !^http://([^.]+\.)*yourdomain\.com
RewriteRule / http://www.yourdomain.com [R=301,L]

```
> -1 votes

---
Tags: redirection
---


# Question
Title: How to scedule a reminder mail for nodes with date field in an oganic group?
I would like to enable all members of an organic group to subscribe to a reminder, that sends an e-mail depending on a date field. To be more specific: The group has a group content with a date field. Now I would like a mail being sent a specific time before this date becomes actual. Would would the best way to do this?

# Answer
When it comes to right on schedule or specific time, you need to have crontab on server. Role of cron tab will be none other than calling your cron.php file which in turn allows all modules to set the cron. But this is half of the process since with core drupal cron process you can not have much control on setting schedule time, so you can use elysia cron module to extend drupal core cron.This was cron part

Now inorder to trigger email you can implement hook\_cronapi() as an example,

```
function mymodule_cron_cronapi($op, $job = NULL) {

  $items['send_email'] = array(
    'description' => 'Send email to group users',
    'rule' => '0 * * * *', // Every Hour at **:00
    'callback' => 'mymodule_email_group_callback',
  );
  return $items;
}

```

cron callback

```
function mymodule_email_group_callback() {
  // load all group content from that content type.
  // loop through all nodes check date
  // if true
  // get all subscribers and loop through them
  // send email
}

```
> 1 votes

# Answer
Off the top of my head I think Maestro can do this with a `Batch Task` or a `Batch Function Task`. In drupal typically `Cron` is setup to run periodically, say every hour or every 15 minutes.

If you truly want a `specific time` for these notifications to go out you need a (cron) task that runs every minute for example and examines if there are notifications to send now as time passes.

Alternatively you could use some sort of Job/Worker queue that Drupal talks to.
> 0 votes

---
Tags: organic-groups, notifications
---


title: edit node attribute in view

text:
# Question
Title: edit node attribute in view
In Drupal 7, is there a way to edit nodes from a view? For example, could I add a checkbox or drop down menu for each node in the view to set a particular attribute of that node?

# Answer
> 5 votes
The EditableViews module should serve your purpose well. Here is part of the module's project page:

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.

---
Tags: views, nodes
---


# Question
Title: How can I tell Drush in which folder should a module be copied?
Is there a way to make Drush download modules into a specified folder besides sites/all/modules (e.g. sites/all/contrib, sites/all/core)?

If this makes a difference, I am using Drush 4.4.

# Answer
I've not tried it but apparently.

```
drush help dl

```

> --destination Path to which the project will be copied. If you're providing a relative path, note it is relative to the drupal root (if bootstrapped).
> 14 votes

# Answer
You can default this to, for example, sites/all/modules/contrib, in your .drush/drushrc.php file.

```
$command_specific['dl'] = array('destination' => 'sites/all/modules/contrib');

```

Also note that you won't be able to exclude the 'modules' part of the path, as Drupal uses this to scan for modules.

There are 6 places this file can live:

> 1. Drupal site folder (e.g. sites/{default|example.com}/drushrc.php).
> 2. Drupal /drush and sites/all/drush folders, or the /drush folder in the directory above the Drupal root.
> 3. In any location, as specified by the --config (-c) option.
> 4. User's .drush folder (i.e. ~/.drush/drushrc.php).
> 5. System wide configuration folder (e.g. /etc/drush/drushrc.php).
> 6. Drush installation folder.
> 23 votes

---
Tags: drush
---


# Question
Title: About drupal_realpath() and PDF Formatter
The PDF Formatter module uses pdftohtml to transform PDF to HTML, and show information.

Changing the module code, it is possible to show images too, but the path used for the image in the HTML markup is wrong.

What can I do to fix it?

The code used by the module is the following.

```
// PDF to html formatter
case 'file_pdf_to_html_formatter':
  $pdftohtml_installed = pdf_formatter_pdftohtml_installed();
  foreach ($items as $delta => $item) {
    $html = '';
      $html = shell_exec('pdftohtml -q -stdout '.escapeshellarg(drupal_realpath($item['uri'])));
      // pdftohtml tends to generate too many non break spaces,
      // replace them with standard spaces
      $html = str_replace(' ',' ',$html);

      // pdftohtml generates a complete HTML file.
      // Drupal only waits for contents between the body tag
      $html = preg_replace('/.*<BODY[^>]*>(.*)<\/BODY>.*/si', '\\1', $html);
    }

    $element[$delta] = array('#markup' => $html);
  }
  break;

```

The output I get is the following.

```
<img src="/var/www/html/drupal/sites/default/files/imgtest.jpg" />

```

# Answer
> 1 votes
To get the web-accessible URL for a local file, you should use file\_create\_url().

```
$html = shell_exec('pdftohtml -q -stdout '.escapeshellarg(file_create_url($item['uri'])));

```

Using it would probably not work, anyway: I think that pdftohtml first tries to access the local file to see if it is a PDF file, and it outputs what you see when the file is an image. I doubt that pdftohtml uses `<img />` for every file that is not a PDF file or that is not able to access.
In your case, `file_create_url('public://imgtest.jpg')` would return `$base_url/sites/default/files/imgtest.jpg` where `$base_url` is the content of the global `$base_url`, which includes the http:// or https:// part. While that would be perfect to be used for the `<img />` tag, it could not be used as filename, since pdftohtml is not probably able to handle a filename starting with http:// or https://. (In other words, it expects the filename of a local file.)

It is probably easier to check if the file is an image, and output the `<img>` tag using the output of `file_create_url()` as image URL in that case, or the output from pdftohtml when it is not an image.

---
Tags: files
---


# Question
Title: When should the dependency from a core module be explicit?
The Standard profile declares the Node module as one of the modules it requires, and so does the Minimal profile. That is not true for the History module, which is required from the former but not the latter.

When should I declare my module as depending from a Drupal core module? Should I assume the installation profile / distribution always requires the module from which my module depends?

# Answer
In all versions of Drupal, if your module depends on another module, you should always explicitly declare it as a dependency.
> 6 votes

---
Tags: .info
---


# Question
Title: How do you implement text color on taxonomy terms
I want to implement different font colors on my taxonomy terms. I have installed and configured my color module version 7.x-1.0-rc1 but still I can't find any result.

# Answer
> 4 votes
Here are steps you need:

1. Install jQuery Colorpicker module.
2. In the vocabulary for terms for which you want to add colours, add a jquery color picker field.
3. So when you create each term, you also select a colour for it while creating. in this way each taxonomy term will have a colour.
4. now in the taxonomy term preprocess template, write something like this to grab the color and pass it as variable.

```
function themename_preprocess_taxonomy_term(&$vars) {
  $colour_code = $vars['taxonomy_term']->field_yourcolorfieldname['und'][0]['value'];
  $vars['colour_code'] = $colour_code;
}

```

Then copy the taxonomy-term.tpl.php to your theme folder, and you will be having $colour\_code variable giving you the colour code of the term. you it to provide an inline css.

Remember, if overriding taxonomy term template is not what you need, or you want to have it elsewhere, whenever you get $term object, you can get the colour code through `$term->field_yourcolourfieldname['und'][0]['value'].`

---
Tags: taxonomy-terms, forms, theming
---


# Question
Title: Form loaded with ajax call not having autocomplete enabled
I have a form (loaded by obiumap function) that have a section loaded ( by function obiumap\_addobj() ) with a $.ajax call from jQuery script (addobj.js) by clicking a button (addobj\_btn). This new section is loaded in an

existing div (addobj-container) but without autocomplete functionality and also without default\_value.

This is main form:

```
function obiumap($form, &$form_state) {
drupal_add_js(drupal_get_path('module', $this->modName) . '/addobj.js');
global $user;

$form=array();
$form['uid'] = array(
'#type' => 'hidden',
'#title' => 'uid',
'#default_value' => '3',
'#id' => 'uid',
);
$form=array();
$form['name'] = array(
'#type' => 'textfield',
'#title' => 'name',
'#id' => 'name',
);
$form['addobj_btn'] = array(
     '#type' => 'button',
     '#value' => t('Add new objects'),
     '#id' => 'addobj_btn'
);
$form['addobj-container'] = array(
        '#markup' =>  '<div id="addobj-container" ></div>'
);
die(drupal_render_children($form));
}

```

This is section definition loaded via ajax:

```
function obiumap_addobj($form, &$form_state){
global $user;
$form=array();
$form['uid'] = array(
'#type' => 'textfield',
'#title' => 'uid',
'#default_value' => '10',
'#id' => 'uid',
);
$form['fldset_addobj'] = array(
'#type' => 'fieldset',
'#title' => t('Add new object'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['fldset_addobj']['objname'] = array(
'#type' => 'textfield',
'#id' => 'objname',
'#title' => t('Object name'),
'#autocomplete_path' => 'obimap/obiumap_addobj',
'#required' => TRUE,
);
 $form['fldset_addobj']['submit'] = array(
'#type' => 'submit',
'#value' => 'Add object',
'#id' => 'addobj_btn'
);
die(drupal_render_children($form));
}

```

and this is addobj.js

```
function addItems(arg1, arg2) {
jQuery(document).ready(function() {
jQuery('#addobj_btn').click(function() {
var formURL = 'obiumap_addobj';
jQuery("#obiumap").submit(function(){
 return false;
 });
    jQuery.ajax(
    {
        url : formURL,
        type: "GET",
        data : { uid: jQuery('input[name=uid]').val() },
        success:function(data, textStatus, jqXHR)
        {
            jQuery('#addobj-container').html(data);
            console.log("###### Drupal.attach #####");
            Drupal.attachBehaviors("#addobj-container");
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
        }
    });

});

});
}

```

I really need autocomplete for that field but I don't now how to activate it.

# Answer
> 0 votes
If you want Drupal's autocomplete, you need to modify form using Form API '#ajax'. If you are doing it with your custom scripts, Form API will not know that field really belongs to your form, and will not handle field's calls.1

The way you should do it is:

1. In your form building function, create element with '#ajax' property, that will be responsible for loading your form part, or add it to existing element.
2. Also in your form building function, add an `if` that will check triggering element (`$form_state['triggering_element']`), and if that was your button, add entry in `$form_state` that new section should be visible.
3. If there is an entry mentioned in 2., output form part you want to be loaded with AJAX.
4. Use AJAX callback function **only** to select and return proper part of the form.

---

1 Simplified explanation, of course.

---
Tags: forms, ajax, javascript
---


# Question
Title: WYSIWYG + CKeditor breaks my <p> lines and mess my paragraphs
After installing the WYSIWYG module + CKEditor / TinyMCE (same result) all my paragraphs are blown away resulting in an uneditable mess. Can you give me a clue how to make it read my paragraph markup? Thanks

# Answer
> 5 votes
I had the same problem and I solved it by allowing paragraph and line break in the configuration of the Filtered HTML:

**Configuration » Content authoring » Text formats » Filtered HTML**

In the "Allowed HTML tags" of the "Filter settings" I added \<p\> and \<br\>

# Answer
> 2 votes
To solve that, you should make the CKEditor disabled by default. Then when you edit an page, Copy the existing text, enable the editor and Paste the text. Now you'll have well formatted html text.

Or you could try Wysiwyg Linebreaks module, it should do the job. I never tried it but maybe you'll be lucky :)

# Answer
> 1 votes
Try configuring appropriate CKEditor profile (it's in Config \> Content Authoring, I believe). There you have settings as per what should be done with paragraphs and empty lines. Also make sure you allow p elements in your Full or Filtered HTML - but that's controlled outside of CKEditor.

---
Tags: 7, wysiwyg
---


# Question
Title: How to create view with user's flagged content?
I created a flag 'Add to favorites' with the Flag module and I'd now like to create a view for the user's profile that sums up all his/her favorite content. I tried to add the relationship **Flags: add\_to\_favorites (by current user)** to my view, but then the favorites of the logged in user appear on every profile page.

How can I solve this?

# Answer
You need to add a contextual filter "Flag: User ID", and provide a default value, "Get UID from URL". Also I think you need too change the relationship to Flags: add\_to\_favorites (any user)
> 1 votes

# Answer
Have you tried adding contextual filters -\> USER -\> get uid from url
> 1 votes

---
Tags: 7, views, flags
---


# Question
Title: Block taxonomy list count with filter by search term?
Currently I have setup a view to display custom search results based on search terms (exposed filter):

/blog/search?keys=user+entered+term

On the page I am looking to show a list of tags with counts based on that search term, for example:

Code (x)
Tutorial (x)
Help (x)

A block has already been created in the view with the following:

CONTEXTUAL FILTERS
(term) Taxonomy term: Name (-\> display summary with count)
RELATIONSHIPS
Content: Taxonomy terms on node
FIELDS
(term) Taxonomy term: Name

While the above does output the taxonomy terms, it displays the counts for all of the taxonomy, rather than filtering it based on the search term.

Seems like I am most of the way there, but would appreciate any thoughts/suggestions anyone could offer.

# Answer
> 0 votes
Contextual Filter Wont do here. Please follow these steps:

1. Add another field "Taxonomy:term name".
2. Under the advanced settings tab, turn on SQL Aggregation.
3. Edit the sql aggregation settings against the newly added field "taxonomy term" to make it "COUNT". Not "COUNT DISTINCT" remember.
4. If there is any sort option, please remove it for this to work. Let the filter remain as it is.
5. Now you will have taxonomy tags, with the number of nodes against each.

---
Tags: taxonomy-terms, blocks
---


title: Create stacked page with panels module

text:
# Question
Title: Create stacked page with panels module
I'm trying to create a stacked page with the Panels module, using flexible layouts. It should look like this:

How can I do this?

# Answer
Simply add 3 rows in the flexible layout by clicking **'Column' \> 'Add row to top/bottom'** in the layout designer to stack the page. Add fluid or fixed regions afterwards in every row.

(Special thanks to @Letharion!)

You can also achieve this without the flexible layouts and do it programatically like @Andrew Welch said. This video can help you in doing that.
> 2 votes

# Answer
You need to create a panels layout. You can find these in the panels module in the layouts folder. I believe you can then create a layouts folder in your theme and copy a layout in there, and work on it. Layouts are simply an includes file with an array of options, a template file, and a thumbnail image.
> 1 votes

---
Tags: 7, panels, theming
---


# Question
Title: Display Suite label below field, instead of above or inline
Pretty straightforward question. Is there a way to get the label for a field to appear below the field? The only options within display suite are inline and above.

# Answer
> 1 votes
theoretically you should create a custom field template file overriding the default one.

If you're using Display Suite Extra

1) On DS field settings select "Drupal default" as field template

2) Override the field template following the standard drupal suggestions (see below)

Unfortunately this will not work due to a bug: http://drupal.org/node/1885480

Instead if you're not using Display suite, you'll be able to override the field template without any problem.

Override a field template is quite easy:

1) copy the "field.tpl.php" from /modules/field/theme directory and paste it on your theme directory.

2) rename the file following the rules documented on this page: http://drupal.org/node/1089656

3) change the field-???.tpl.php content moving the label below the field content like:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
</div>

```

# Answer
> 0 votes
On Drupal 7, Displaying fields inline can albo be done with the popular Compact Forms module. You select the CSS IDs of the forms on which you wish to perform the change. Here is the admin page:

Another, less stable option is the In Field Labels module.

---
Tags: display-suite
---


title: Add Admin User in Drupal 6

text:
# Question
Title: Add Admin User in Drupal 6
I have an old site built in Drupal 6 and I need to add a new admin user. I cannot give out user #1 and need a new one.

As far as roles go, I have authenticated and anonymous.

Is it as simply as adding a new role and granting full access or is there something a little easier I can do to accomplish this?

# Answer
> 2 votes
Admin role with this module you can add more **super users**.

> This module is a little helper to maintain an administrator role which has all available permissions. By default, Drupal only has one super user and this module helps improve this drastically.

---
Tags: 6, users
---


title: Rewrite URL not working

text:
# Question
Title: Rewrite URL not working
In Drupal 6 I used the following snippet of code in my .htaccess file to extract information from a non-existent URL and pass it to an existing URL in a GET form. However, it isn't rewriting the URL with my Drupal 7 installation and when I visit a URL the should be rewritten, I just get a Page Not Found error! I have cleared all caches and even tried different browsers:

```
# Custom Rewrite  ScriptOptions +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^home/code/([^/]+) home/software?code=$1 [L,NC,QSA]

```

I have placed the code just after the default handler is set.

Could anyone tell me why this code isn't working? Should I be doing this a different way in Drupal 7?

UPDATE: Please see the question I asked on Stackoverflow to get this code working with Drupal 6 - https://stackoverflow.com/questions/10765799/rewrite-a-url-to-include-get-data-with-drupal

# Answer
> 5 votes
Handling of "Clean URLs" has changed from Drupal 6 to Drupal 7 in a way that affects Apache RewriteRule.

I'm not sure if that is what has bitten you since I don't recognise `home/software?code=$1` as a typical Drupal URL. But I've found that in Drupal 7 I need to rewrite to a "unclean" URL.

For instance, the following will work in Drupal 6, but not in Drupal 7:

```
RewriteRule ^home/code/([^/]+) home/software/node?code=$1

```

In Drupal 7 you must *not* rewrite to a clean URL destination, even if you have clean URLs enabled. The following will work in Drupal 7:

```
RewriteRule ^home/code/([^/]+) ?q=home/software/node/&code=$1

```

# Answer
> 0 votes
Very simple

1. Goto .htaccess file in your drupa7 folder(ie your project folder. it may in in www/drupal\_project/ or public\_html/drupal\_project/).
2. .htaccess is a hidden file. So go to this this directory structure www/your\_project/(or public\_html/your\_project/) and press ctrl+h.
3. You will get all hidden files including .htaccess file.
4. in .htaccess file, go to line number 106
5. # RewriteBase /drupal uncomment this line. Replace drupal by your project folder.
6. If you are not administrator or if you have an account and you working from that account, specify like this, #RewriteBase /~username/your\_project\_folder
7. Save the file
8. Go to admin/config/search/clean-urls this page.
9. If everything is ok, you will get Enable clean URLs checkbox.
10. Enable it and now you have clean URL in your site.

---
Tags: 7, uri, .htaccess
---


# Question
Title: How to load one certain js before all others?
We are struggling around here with SVG in IE8. Amongst other approaches we'ld also like to try the SVG Web Toolkit. In it's quick start guide they say:

> To use SVG Web, you must drop a script tag into your HTML page. This *must* be the first script tag on your page.

The JS is now loaded by a custom module. I tried

```
drupal_add_js($modulepath . '/libraries/svg.js', array(
   'group' => JS_LIBRARY,
   'weight' => -1000,
   'every_page' => TRUE));

```

When I vary these options it's sometimes higher, sometimes lower. The above code makes it the highest I can get it. But there still are quite a number of scripts loaded prior to it.

How can we ensure the svg.js to load first? Is there maybe a way to do it with `drupal_add_js` in our custom module?

# Answer
Can you try with hook\_js\_alter
> 0 votes

# Answer
You can install the js\_injector module in which you can choose the priority of your .js file
> 0 votes

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


# Question
Title: Do I need to sanitize a user input textfield used in a mail body?
I have a feature on my site where a user is allowed to edit a textfield is a Drupal form (built using the D7 Form API) and then send the contents of that textfield as (part of) the body of an email to another user. I use drupal\_mail to send the mail.

The textfield is saved in the database, and I rely on the Form API to protect against SQL injection. The textfield is never rendered on the screen outside the textfield widget, so "dangerous" HTML tags and PHP/JavaScript injection is not a concern (I hope).

I use `DefaultMailSystem` as mail backend.

Given that the user can type *anything* in this textfield, is there any need to sanitize this user input before it is included in the email body and sent?

# Answer
> 4 votes
There are two reasons to use Drupal's text filtering system: security and proper formatting of the information for the context.

In reverse order:

* For formatting: if you use something like the markdown filter or limit with html tags can be used for simple sanity (i.e. no h1) then you want to use a filter that removes that.
* For security: you want to remove malicious code if it is being displayed in an environment where that matters. In the case of email, the relevant DOM is the email client which can sometimes be a domain. However, if it is a security weakness to that email user to get javascript...that is a problem with their client. Since anyone can send any email to any address with any (malformed) contents it is not a major consideration of e-mail processing to ensure the body is "safe" (without scripts). See this discussion on g.d.o/security about sanitizing text in email bodies

That said, you don't want your system to be useful for spam.

* Consider using the flood\_control system.
* Consider adding an introduction and closure to your email message to make it less useful for a spammer. For example "This email was sent from example.com. Your friend said: \_stuff\_here\_. If you have questions contact your friend and not example.com"

There is more to e-mail than the body, of course. E-mail headers can be a vector for attacks, since someone can use a newline as part of the "to" address and then append new headers to send as many mails as they want to whomever they want, pretending to be from whoever they want, hurting your domain's reputation in the process.

One other side-note:

> The textfield is saved in the database, and I rely on the Form API to protect against SQL injection.

SQL Injection protection should come from proper use of methods and arguments in your db\_insert or db\_query function. It does not come from the Form API.

# Answer
> 2 votes
It depends on the mail backend you are using. `DefaultMailSystem` perform basic sanitization on send, but it cares only about mail specification and ignores the fact that body might be HTML - that's on you. So you are guaranteed what you send will be formally valid e-mail, but not that it will be valid HTML. Exact part about body sanitization is:

```
// Note: e-mail uses CRLF for line-endings. PHP's API requires LF
// on Unix and CRLF on Windows. Drupal automatically guesses the
// line-ending format appropriate for your system. If you need to
// override this, adjust $conf['mail_line_endings'] in settings.php.
$mail_body = preg_replace('@\r?\n@', $line_endings, $message['body']);

```

And that's it, as mail is pretty accepting format and sets stricter requirements on other fields - NOT on body.

Using `drupal_mail()` is safer than using backend directly, as it calls format method:

```
// Format the message body.
$message = $system->format($message);

```

And default's format method strips the HTML:

```
  // Convert any HTML to plain-text.
  $message['body'] = drupal_html_to_text($message['body']);

```

The big question is - how much do you trust `drupal_html_to_text()`? It is there to made text valid, but it never claims it is a safeguard against malicious misuse. As far as I understand it's code, it should be reasonably safe in most cases, but as far as I remember there was some link related holes in mail readers that could be abused anyway.

**TL;DR** Basic sanitisation is done but there still might be some attacks possible.

---
Tags: emails, security, notifications
---


title: More options for managing node display

text:
# Question
Title: More options for managing node display
I am trying to clean up the node pages and am finding very few options under the Manage Display tab. Do I have to dig in to the code and css to get some more control or is there a module that allows for greater customization in this area?

I am thinking about options similar to what Views allows.

* Adding relationships to pull in related content. e.x. author name from profile instead of using username.
* A specific example: One content type has a photo and alot of text, and I want the text to wrap around the photo.

# Answer
In general, as Clive said it is difficult to give answer to a question that broad in scope. But in general there are two broad directions:

1. Use Modules like Panels and Display Suite - These allows customizations in node pages by allowing you to chnage layout, add different contents etc.
2. Follow custom theaming path. this involves writing modifying the preprocess function and modifying the node.tpl.php

Any more specific info will require you to give out more details in terms of what you want exact in terms of layout and "clean up"
> 2 votes

---
Tags: nodes, entities
---


# Question
Title: how to use a view to node field based on url
I have a content type A which has a node reference to another node (type B). I want to create a block (using views) to display the content of that node reference in a side block on its respective node page (type B).

I think this might be possible with either contextual filters or relationships, but as I have never used either, I'm not sure exactly how to do this. If I could use these, I imagine that I could use the url as a filter.

# Answer
I am assuming, you have a node of type A, that refers to a node of type B through a node referance field "field\_noderef" attached to node A. You want to display the details of node A when you visit node B.

1. Create a block type view. Filter as content type = A
2. Create a contextual filter "field\_noderef", set a default value of "get NID from URL".
3. Display the block in node page of content type B \*this part is important.
> 2 votes

# Answer
You can do that by creating a view of Type A and than adding a relationship with Type B as following:

* Create a view of content type A and choose it to be of fields type.
* Add contextual filter for node id. (This will play a major role to filter out the content on the basis of argument \[nodeid\] you will be entering)
* Add relationship with content type B. (Entity Reference: Type B)
* Now add the fields for Type B (and apply the relationship with the Type B).
> 2 votes

# Answer
I actually was able to get this result without Views at all. I simply did a variable set for the field I needed from inside the node template. I then created a custom block and retrieved the variable with variable\_get.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How can I output markup fields or descriptions in my Webform email?
I have a webform that requires a markup field, or alternatively, a description to be carried through to the email or "View form submission" page.

Typically one can put the token `%email_values` in the email template which will give a list of fields and their labels that are submitted to the form - but this doesn't seem to include markup fields, or field descriptions.

I have tried using other tokens such as `%post` or `%value`. For instance, I have a markup field with machine name "foo" in a fieldgroup "bar", and putting `%value[foo][bar]` just dumps the string `[foo]` into my email.

So is there a way to reference these parts of the webform?

# Answer
Did you tried using this? If the markup field `foo` sits within the fieldgroup `bar`, you need to inverse the order and the last `%` shouldn't be there.

```
%value[bar][foo]

```
> 1 votes

---
Tags: 7, webforms
---


title: $content is only showing array text

text:
# Question
Title: $content is only showing array text
I have a theme, and for the life of me can't figure out why $content is rendering "array". I have switched to two other themes (framework and seven, and my new theme is based off of the framework theme that is working).

Here is an example of the theme code:

```
    <div <?php if ($left): ?>id="maincolright" <?php elseif ($right): ?>id="maincolleft" <?php else: ?>id="main" <?php endif; ?>class="nobg node-<?php print $node->nid; ?>">

    <?php if ($tabs): print '<div id="tabs-wrapper" class="clear-block"><ul class="tabs primary">'. $tabs .'</ul>'; endif; ?>
    <?php if ($tabs2): print '<ul class="tabs secondary">'. $tabs2 .'</ul>'; endif; ?>
    <?php if ($tabs): print '<span class="clear"></span></div>'; endif; ?>
    <?php if ($show_messages && $messages): print $messages; endif; ?>
    <?php print $help; ?>
    <?php print $content; ?>

</div>

```

So $content is there, and it should be fine, but on any pages I view, for instance, the page render, the edit page, or even my devel page, show only 'array'. See the screenshot:

Has anyone come across this?

# Answer
> 1 votes
`print()` is a command that doesn't work with arrays. `print_r()` will print out arrays for debugging but what you want is `print render($content)`. Drupal uses large render arrays to output content, and they cannot be printed directly.

# Answer
> -1 votes
some other people are saying the modules have a bug where you have to use underscore instead of dash in the div definitions; try tabs\_wrapper for example

---
Tags: 6, theming
---


title: Change markup of single form field

text:
# Question
Title: Change markup of single form field
I have constructed a form manually using the Form API. I have one field in particular that needs to have it's markup changed a tad.

The #prefix/#suffix output should come immediately before/after the input control. I think the output currently looks like:

Can I override the themeing for a single field using something like:

```
$form['control'] = array(
  '#theme' => 'control_field',
  '#title' => 'Some title',
  '#type' => 'textfield'
);

```

Do I then implement MYTHEME\_custom\_theme in the templates.php???

Do you know of any exmaples I might use?

I tried adding:

```
function theme_control_field($variables) {

}

```

This did not seem to work...also I need control over all the markup for this field not just the field control but I need to relocate the prefix/suffix output as well!?!

Regards, Alex

# Answer
> 3 votes
You can have a complete custom HTML for a particular field by defining a `#theme` and setting `#theme_wrappers` with an empty value.

```
$form['control'] = array(
  '#title' => 'Some title',
  '#type' => 'textfield'
  '#theme' => 'YOURMODULE_control_field',
  '#theme_wrappers => array(),
);

```

Then Drupal needs to know about this new theme by implementing the `HOOK_theme`. You can either work with a template file or generate the HTML within the `theme` callback function

```
function YOURMODULE_theme()
{
    return array(
        'YOURMODULE_control_field' => array(
            'template' => 'templates/control-field', // if you want to have a tpl file, templates/control-field.tpl.php using the $element variable for your textfield element
            'render element' => 'element',
        ),
    );
}

// If you dont want to use the template file
function theme_YOURMODULE_control_field($variables)
{
    $element = $variables['element'];
    // $element is here your form textfield element, this function return HTML to generate
}

```

---
Tags: theming, entities
---


# Question
Title: Is there any way to force blocks created by views to display even when there is no result?
I have similar question with "Display a block even if it is empty" about blocks generated with views 3.5.

# Answer
Views has a somewhat hidden feature for setting the behavior when you have no results.

If you edit the view and click on **Advanced**, you will see some new settings:

Click on `add` next to **NO RESULTS BEHAVIOR**. You will then get a modal with a ton of choices. You should be able to use the textarea or markup options to plop in a   This should force the block to not be "empty". You could also set a message, etc.

You can also always show the advanced options if you visit admin/structure/views/settings

I typically always set "Always show the master display" and "Always show advanced display settings". There are some other useful settings on admin/structure/views/settings/advanced
> 1 votes

# Answer
In addition to the NO RESULTS BEHAVIOR, if you have a Contextual Filter, make sure that the default value is set when it is not available from the URL. Otherwise the view may be hidden.

For example, I had to update the "User Orders" view provided by Commerce and change the default value to the logged in user, instead of "hide view"
> 0 votes

# Answer
In addition to what @MPD and @andrewtweber said, you can add a header and footer that will appear when there are and are not results for your view.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Difficulty to list taxonomy terms in a block for specific content type (d7)
I have made a page using views to list a specific content type. Then I wanted to make a block to list a taxonomy vocabulary in a sidebar in order to sort the posts according to terms.

The problems I am facing are:

1. If I select the block to appear for specific content types, the block doesn't show
2. I am having a multilingual website and the block shows terms in both languages, how do I choose to show the terms in the current users language?
3. I have also tried the module taxonomy menu but it also lists terms in both languages and doesn't show for specific content types

Any help would be highly appreciated.

# Answer
> 0 votes
To get the block to appear on certain content types you will need to get the common URL for the content types you are looking to put it on. You may have to use a module like pathauto to set better URLs for your content. For example if you are on an article content and the URL is www.example.com/article/3 you would go to the block configuration and at the bottom choose to show blocks only on certain pages. Then in the text box type the urls of the content types you want them to show on. Again as Article content type as an example you would enter: article/\* or just simply article\* like so:

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


title: Install and Configure XHProf (Ubuntu)

text:
# Question
Title: Install and Configure XHProf (Ubuntu)
**Problem**

I'm trying to use XHProf but I'm getting horrible php error every time it runs.

```
Warning: Invalid argument supplied for foreach() in xhprof_compute_inclusive_times() (line 1670 of /var/www/drupal/sites/all/modules/XHProf/xhprof.inc).
Warning: Invalid argument supplied for foreach() in xhprof_compute_flat_info() (line 1644 of /var/www/drupal/sites/all/modules/XHProf/xhprof.inc).
Warning: Invalid argument supplied for foreach() in theme_xhprof_overall_summary() (line 367 of /var/www/drupal/sites/all/modules/XHProf/xhprof.module).

```

The problem is solved here because the temporary folder doesn't exist, however mine does.

**Set-Up Server Side**

I'm running a fresh Ubuntu Server 13.04 with Drupal 7.

Install xhprof using `pear` following the instructions here. I also added a temporary directory to php.ini, which I created manually.

```
extension=xhprof.so
xhprof.output_dir="/var/tmp/xhprof"

```

**Drupal Set-Up**

I have both the devel installed and I also installed the XHProf module.

In `admin/config/development/xhprof`, I enabled profiling of all page views and drush requests.

On following an xhprof link I get the error above.

# Answer
Good god Batman. That was incredibly frustrating. Here's a guide to getting xhprof working. (Note: I am very new to Linux. I'm not sure if the permissions I use are safe, or whether there is a better way of doing it. I'd only do this on a test environment.)

IMPORTANT: It won't tell you anything about how to interpret it. I have no idea how to, I'm just happy it works.

**Getting XHProf Working**

**1. What operating system are you running?**

Mac or Linux?

It's possible.

Windows?

Probably not. To run xhprof on windows you have to have a compiled dll. There's a link to one in this thread, but I always had compatibility issues with it when I tried to use it on XAMPP.

I think it was compiled with a different version of Apache.

**2. Getting it working on Ubuntu**

It's possible on Mac. Here are two useful links:

http://www.lullabot.com/blog/article/installing-xhprof-mamp-and-php-52-mac-os-106-snow-leopard http://www.midwesternmac.com/blogs/jeff-geerling/getting-xhprof-working-well

But I haven't done it. I managed to get it working on Ubuntu Server 13.04, although I think any recent version of Ubuntu Server would work.

I set-up my server on VirtualBox. VirtualBox is free but it might take a bit to learn how to set it up.

**3.Installing XHProf**

I'm going to assume we have a fully functioning Ubuntu Server.

First we need to install pear. We'll use this to install XHProf.

```
sudo apt-get install pear

```

We follow this up with phpdev which is also needed.

```
sudo apt-get install php5-dev

```

If these commands don't work and I've got them wrong, just go straight ahead with:

```
sudo pecl install -f xhprof

```

Ubuntu will tell you what you're missing and give you the prompt to install it. Once you've got all the dependencies install xhprof.

You might get an error on installing xhprof, it'll try to download the beta and fail. In that case try:

```
sudo pecl install -f xhprof-beta

```

Hopefully xhprof is now installed.

Now we need to configure it. Open your php.ini which is at `/etc/php5/apache2/php.ini` and add the following two lines under the extensions section:

```
extension=xhprof.so
xhprof.output_dir="/var/tmp/xhprof"

```

The second line sets the output directory. If this folder doesn't exist you'll have to create it.When you've done that reboot apache using

```
sudo service apache2 restart

```

**4. Checking if XHProf is running**

Now we need to check if that worked.

Test 1:

Enter `php -m`

If you see xhprof in the list you're good to go. If not, don't worry, try this instead to check if it's working:

Go to your webroot `/var/www/` and create a php file with only:

```
phpinfo();

```

Save it as phpinfo.php. Open this in your browser and you should see PHP information. Search for xhprof and if you see this then it's running.

**5. Getting it working with Drupal**

I couldn't get it working with the Drupal module. So instead I'm going to tell you how to get it working with the devel module.

First some config that I borrowed from here. I didn't really follow this part, but it works so gift horse and all that.

Create a new config file with the following command:

```
sudo nano /etc/apache2/conf.d/xhprof.conf

```

and insert the following code.

```
alias /xhprof_html "/usr/share/php/xhprof_html/"

```

Then we possibly need to create a symlink to our xhprof\_html folder. So just in case set this:

ln -s /usr/share/php/xhprof\_html /var/www/xhprof\_html

This will create a folder in your webroot that points to the existing xhprof file. Then in your browser you can open http://mywebsitehere.com/xhprof to see all the runs you've made.

Then restart apache. Now it's time for a little devel config. Go to the devel settings, enable xhprof and set:

```
xhprof directory = /usr/share/php

XHProf URL = /xhprof_html

```

Now at the bottom of each page you should see a little link to xhprof.

And clicking it should take you to a page that looks like this. You're done. Congratulations!

If that didn't work and you're getting run errors it's probably because Drupal doesn't have permission to write to the tmp folder that we set earlier so enter:

```
sudo chown -R www-data /var/tmp/xhprof

```

And hopefully that works. We're done. Hoorah!

Unless you want graphing functions. Thankfully that's as easy as:

```
sudo apt-get install graphviz
sudo service apache2 restart

```

And now you should have graphing functions. Hopefully that helps!
> 34 votes

---
Tags: 7, debugging
---


title: Why is my webform returning a 404?

text:
# Question
Title: Why is my webform returning a 404?
I have several webforms on the site, and all work as intended, except one, which throws a 404. Everything seems to be as it should, so I'm not even sure where to start.

# Answer
While doing the research to add the additional information, I discovered the uid for the node was set to 0. Updated that to 1 and the webform now appears.
> 0 votes

---
Tags: webforms
---


title: Change the link of a view block

text:
# Question
Title: Change the link of a view block
Hi I need to change the url path of the view which appears to be a block also,its a button and I want that it redirects to the correct URL, how do I change it? Please help me.. Answers and directions will highly be appreciated thanks.

# Answer
> 0 votes
Blocks do not have URLs. Pages that blocks are on have URLs.
Check the gear icon when you hover over the view area.

If it says configure block, you are on a page created somewhere else and depending on how it was created may need to edit the code where it is defined in hook\_menu() or if it is a page node, you can just go to admin/content and search for that page, and at the bottom you will see URL settings.

If it says does not say configure block and only edit view, then that page was likely created by that view you are about to edit. In this case you can click Edit View and in the middle of the window you will see Page Settings section with a Path field. You can edit that Path field which is the URL of the view.

---
Tags: views, uri
---


title: let user create content as another user

text:
# Question
Title: let user create content as another user
My company has a website with a blog, and we have a virtual assistant. Our process is that after writing the blog we have our virtual assistant proof read for grammar and spelling errors. what we would like to do is to have our virtual assistant log into our site as herself but be able to post the blog article as one of us.

Is there a module that allows for this kind of ghost posting?

# Answer
> 3 votes
Using node hooks to set the user will work, but what you are suggesting is really what is normally called "workflow" in content management systems.

There are a few ways to do workflow in Drupal, but the most common for Drupal 7 is probably using the Workbench suite of modules. In particular, Workbench Moderation would be the most beneficial module for your situation.

You would set up a few different roles (writer, editor, proofreader, etc) for your users. You would then set up various workflow states (Draft, Pending, and Published are a good start). Then, you define which roles can push nodes through which states of the workflow. For example, you may say that only writes can push from Draft to Pending, and proofreaders can only push from Pending to Published.

In the long run, this will give you the most flexibility as your current situation evolves and changes.

# Answer
> 2 votes
First, while it is not mentioned, I assume that the content already exists as a node in the database (typed in by the original author), but that it shall remain unpublished until the assistant has corrected it. The following is based upon that assumption.

You can do this by creating a new role, e.g. `Assistant`, and then assign that role to the person you refer to as a "virtual assistant".

Then you download, install and enable the following module: View unpublished.

You now need to grant that role the following two permissions: `View unpublished` and `Edit any content` (both for the content types you want to enable this for.) The settings for permissions and roles is under *Home » Administration » People*.

Now, the assistant should be able to navigate to `example.com/admin/content` and view the unpublished nodes queued up for review. The assistant should be able click on a node and the the edit tab to edit it, and, when done, toggle the `Published` switch to publish the corrected node after review. The byline will still be that of the original author, not of the assistant.

(If the node shall *not* remain unpublished until corrected, the workflow is even simpler. Then you do not need to install a module, just grant the `Assistant` role the permission to `Edit any content`, and you're set to go.)

PS: Your question ask for a module that let your assistant log into our site as herself but then post a blog article masquerading as another user. I doubt that this is what you're looking for (please edit your question to clarify this - also see my comment below your question), but *if* this is what you're after, there exists a module named Masquerade that can do this.

# Answer
> 1 votes
I am assuming "virtual assistant" not as program but as a "real assistant". Having said that my idea is having user reference field on your blog post which will be a select list and when assistant will be posting the blog, she will select the user from the user reference field and then implementing hook\_node\_presave() you can easily assign the author to the blog post as the user selected in the user reference field.

OR

you can give a try to node override options module which allows to have granular permissions for user role to change node author information.

# Answer
> 1 votes
Can you use the module Masquerade? https://drupal.org/project/masquerade

I use it on one of my projects for this exact reason. Here's how it would work on my project to set up the permissions:

* Login to your site as an admin
* Go to People \> Permissions
* Scroll down to Masquerade (you have to already have enabled the module). Here you can test what permissions work for your users. You do have to assign permissions to a role. Maybe make a specific role for this type of user (https://drupal.org/node/120614)

As an admin, I can allow a single user to masquerade as another user by:

* Login to you site as an admin
* Go to your People page and find the user you want to allow to masquerade as others. Select that user.
* My system has a prominent "edit" link to edit the profile. Select this.
* You will see a "Roles" option. Since you have already set the roles that can have Masquerade as an option, select the role you wish to assign to this user.

That user should now be able to masquerade. You might have to do some addition setup by assigning the Masquerade to a block or panel that is only visible to specific roles.

Hope that helps!

---
Tags: 7, nodes
---


title: Connect Drupal to external data base

text:
# Question
Title: Connect Drupal to external data base
Is there a specific module or a definied mechanism to connect a given external data base to a view?

---

### settings.php

```
$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd3js',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

  'NewDataBase' => array (
    'default' => array (
      'database' => 'NewDataBase',
      'username' => 'username',
      'password' => 'password',
      'host' => '131.188.76.40',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

This is the module that is related to the view.

```
 /**
  * @file
  * D3 views module file.
  */

 /**
  * Implements hook_views_api().
  */
  function d3_views_views_api() {
   return array(
   'api' => 3,
   'path' => drupal_get_path('module', 'd3_views') . '/views',
  );
 }

 /**
  * Implements hook_theme().
  */
function d3_views_theme() {

   return array(
   'views_ui_style_d3_options_form' => array(
   'render element' => 'form',
   ),
 );

}

/**
 * Implements template_preprocess_views_ui_style_d3_options_form().
 */
 function d3_preprocess_views_ui_style_d3_options_form(&$vars) {
   drupal_add_css(drupal_get_path('module', 'd3_views') . '/css/views_ui_style_options_form.css');
 }

/**
 * Theme the form for the table style plugin.
 */
 //declarition of the variables related to form (tree)
 function theme_views_ui_style_d3_options_form($variables) {
 $form = $variables['form'];

 $output = drupal_render($form['library']);

 $header = array(
 t('Field'),
 t('Display'),
 t('Aggregation'),
 t('Data type'),
);
 $rows = array();
 foreach (element_children($form['columns']) as $id) {
 $row = array();
 $row[] = drupal_render($form['columns'][$id]['name']);
 $row[] = drupal_render($form['columns'][$id]['display']);
 $row[] = drupal_render($form['columns'][$id]['aggregate']);
 $row[] = drupal_render($form['columns'][$id]['type']);

 $rows[] = $row;
 }

 $output .= '<fieldset><legend>Data</legend>' . theme('table', array('header' => $header, 'rows' => $rows)) . '</fieldset>';

 $output .= drupal_render_children($form);
 return $output;
}

```

This module also has and I didn't know exactly where to connect to the database.

# Answer
> 2 votes
You will need to add the following configuration in your settings.php file

```
$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
);

```

Refer to settings.php for the array options.

Now if you are using a custom module you can use the following in your module to switch between the 2 db's

```
// Use the database we set up earlier
db_set_active('my_other_db');

```

and if you want to move back to the default db

```
// Go back to the default database,
// Remember to go back to the drupal default version or drupal will not be able to access its data
db_set_active();

```

Also refer to https://drupal.org/node/18429 for more information.

There is one more of doing it if you do not want to do the db\_set\_Active() all the time.

So you define the connection in your settings.php like in the first step. Then in the module you can directly do the following

```
$query = Database::getConnection('default', 'my_other_db')
           ->select('source_table', 'st')
...

```

---
Tags: views, database
---


# Question
Title: How to construct database query with conditions that include 'and' and 'or' clauses?
I am converting a Drupal 6 module to a Drupal 7 module. I have come across the following database query that I don't know how to convert to the new Drupal 7 format.

```
$sql = "
  SELECT id
  FROM {room_reservations}
  WHERE (
    (deleted = '%s' AND room = '%s' AND date = '%s' AND time = '%s' AND length > %d)
    OR
    (deleted = '%s' AND room = '%s' AND date = '%s' AND time = '%s' AND length > %d)
    OR
    (deleted = '%s' AND room = '%s' AND date = '%s' AND time = '%s' AND length > %d)
  )
";

```

Although the where clauses do repeat itself, each substituted value in there is different. My question is how does one construct such a statement in Drupal 7 using the new database API? Can you mix and and or statements?

Thanks.

# Answer
> 2 votes
Here's an example, taken from statistics.pages.inc

```
$query = db_select('accesslog', 'a', array('target' => 'slave'))->extend('PagerDefault')->extend('TableSort');
$query->join('users', 'u', 'a.uid = u.uid');

$query
  ->fields('a', array('aid', 'timestamp', 'url', 'uid'))
  ->fields('u', array('name'))
   ->condition(db_or()
    ->condition('a.path', 'node/' . $node->nid)
    ->condition('a.path', 'node/' . $node->nid . '/%', 'LIKE'))
  ->limit(30)
  ->orderByHeader($header);

```

What you want to notice, is the use of db\_or(), which adds an OR to your query. There is also the similar db\_and(). You can mix and match the two as much as you want. The db\_and() documentation also has comments with examples of the two used together.

---
Tags: 7, database
---


title: multiple keyword match with db_like

text:
# Question
Title: multiple keyword match with db_like
I am using db\_select for database query, following code works fine when $keyword is any string

```
 $result = db_select('my_table', 'mt')
        ->fields('mt')
        ->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE')
        ->execute()
        ->fetchAllKeyed();

```

How can I make the same query working when $keyword is suppose to be an array of strings like ("del","mum") ,if my\_column is location column so query will return me places like Delhi, Mumbai.

# Answer
> 9 votes
You can build your query while looping through each keyword and adding this as an OR condition.

```
$db_or = db_or();
$query = db_select('my_table', 'mt');
$query->fields('mt');

foreach ($keywords as $keyword) {
    $db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE');
}

$query->condition($db_or);
$results = $query->execute()->fetchAllKeyed();

```

---
Tags: database
---


# Question
Title: Drupal 7: how to display the content of the field without the label in node--type.tpl.php?
I created a content type called Community (machine name: community).

So I created file `node--community.tpl.php` to rearrange the fields.

I can do it like this...

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

```

it prints (with Phone in bold)...

```
Phone:
(888) 555-555

```

But I just want it to display the raw value with no label and no surrounding HTML. I just want to print `(888) 555-555`.

How can I do this?

# Answer
You can do this by editing the Content Type and managing the display of your fields - click the Manage Display tab.

Once in there, you can change the label to hidden.

See screenshot:
> 4 votes

---
Tags: theming, nodes
---


# Question
Title: Using ajax to process textfield in Drupal 7
Inside of a hook\_form\_alter function, I want to leverage the #ajax property to modify/update database tables without leaving the form... In other words, I want the user to be able to fill in the field and either "tab", "click" or "enter" and have ajax respond.

The response should be an update of that field being displayed as well as an update to the DB...

If I can get the call back to wakeup, the DB call is easy. And hopefully the form displays that new data. Code I have so far is:

```
$form['license'] = array(
  '#type' => 'textfield',
  '#title' => t('License'),
  '#size' => 20,
  '#default_value' => 'default license',
  '#required' => FALSE,
  '#weight' => 10,
  '#ajax' => array(
    '#callback' => 'license_fillin_js',
    '#event' => 'change',
    .
    .
    .

  ),

```

So far, nothing seems to be waking up the callback.

This is probably very simple! Right?

# Answer
change it to and then try again.

```
$form['license'] = array(
  -
  -
  '#ajax' => array(
    'callback' => 'license_fillin_js',
    'event' => 'change',
    .
    .
    .

  ),

```

As an example you can check this link
> 2 votes

---
Tags: forms, ajax
---


# Question
Title: Change page.tpl.php in a shared theme based on domain
I keep finding snippets like this:

```
function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'mydirectory') {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

```

But, what I'm trying to figure out is how to switch to a different page.tpl.php file entirely within the same theme when a domain is different.

So if I had:

`http://www.example1.com/stuff` AND

```
http://www.example2.com/stuff

```

Using domain access module and other rules, the content is slightly different for example1 than example2 but the paths are identical so I can't simply access arg\[0\].

The ham-fisted way is to dupe the theme, change the name and be on my way but I'm sure I'm not getting something...the actual basic page.tpl.php template has to be modified because of existing content at the same path but different domain.

On example1, there are no side bars for example so those regions are not in the .info file nor rendered but on example2, there are sidebars. However, since I want to apply an existing theme, I just thought I'd restructure the actual page.tpl.php file for example2 so as to keep the majority of css/jquery and custom html implemented into the theme.

Is this more trouble than just duping the theme, rename and make the changes there?

# Answer
You could do aomething like this:

```
function MYTHEME_preprocess_page(&$vars)
{
    $domain = domain_get_domain();

    $vars["theme_hook_suggestions"][] = "page__" . $domain["domain_id"];
}

```

Feel free to explore what other values are in the $domain array and use it accordingly to make your theme suggestions as complicated as required. The above example is just to demonstrate injecting domain information.

There are developer notes on the Domain Access module as well which you may find useful
> 3 votes

---
Tags: theming
---


# Question
Title: Product catalog in views that is hierarchical but not mutually exclusive
I am trying to get views create a product catalog in taxonomy that is hierarchical but categories are not mutually exclusive. For instance, lets say my hierarchy looks like this:

```
+---Color
|   +---Red
|   \---Blue
|       +---Sky Blue
|       +---Navye Blue
|
+---Shape
|   +---Cirlce
|   \---Quadrilateral
|       +---Rectangle
|       +---Square
|
+---Size
|   +---1"
|   +---2"
|   +---3"
|   +---4"

```

When browsing the view I want visitors to be able to drill down through the categories while still having the other categories exposed to be filtered without requiring the user to select size before shape or vice versa. The site that is inspired me the most in this project is this: McMaster-Carr. As you can see in that link, just browsing through the washer section is quite an adventure.

# Answer
> 0 votes
I think what I'm looking for here is a faceted search, which I can use through the Facet API module. It looks like this

# Answer
> 0 votes
I would try to achieve this with an exposed filter in views, 'Has taxonomy terms' or 'Has taxonomy terms (with depth)' for example. Use this as an exposed filter (dropdown with multiple select) in a page display. In the advanced settings in views you can choose to expose the form in a block. You can add this to the left sidebar and activate 'autosubmit'. So everytime they change something the results get filtered.

Since dropdown is not that nice, I would try on basis of this post https://stackoverflow.com/questions/9208997/drupal-7-creating-a-taxonomy-filter-using-checkboxes to change it to checkboxes.

---
Tags: views
---


# Question
Title: Discount for specific user group in Drupal Commerce
I need to create 3 user groups and all of these groups must to have discount on all products in percent.

Example:

Group1 have discount of 10% on all products, Group2 have discount of 13% on all products, Group2 have discount of 16% on all products

Any idea how to do that?

# Answer
Wait, wait, wait. That video tutorial referenced in the currently accepted answer is very outdated and unnecessary. All you need to do is create a new product pricing rule and use the "Multiply the unit price by some amount" line item action. Multiply it by .9 for a 10% discount, .87 for a 13%, and .84 for a 16% discount. Then just select the "Discount" price component (or else use a module to define a new price component type) in the action so it appears as expected in order total price breakdowns.

The only reason abusing the tax system was recommended at the time of that video recording was because you could not specify the price component type in the rules action. That has long since been changed, but alas the video still gets linked to quite a bit.
> 8 votes

# Answer
Just add a product pricing rule with a user role condition, See this video tutorial for adding pricing rules.

Below are the steps to achieve discount for product pricing

* Go to `store-> Configuration-> taxes` and then add a tax type.
* Name it something like "Discount Offer"
* And then Check the option "Display taxes of type inclusive in product prices" and then save it.
* Go to tax rate tab and add the discount amount like "-0.10" and choose the type you created "Discount Offer" and save it.
* and then make a pricing rule for a user role condition.
> 1 votes

---
Tags: commerce, users
---


# Question
Title: Hook to import entity data in custom module installation in Drupal 7
What would be 'the best' hook function to use in the custom module installation to import entity data? This is supposed to be a one-time activity during the module installation only, after entity schema is built in the database and entities are initialized (to be able to use Entity API in the data import).

# Answer
> 1 votes
For one time import of data, when installing a module, use `hook_install`. This can be used to populate the database just after tables are created, provided your module also implements `hook_schema`.

You do not want to use `hook_enable`. If you used this, the database would be re-populated every time the module was re-enabled after being temporary disabled.

# Answer
> 0 votes
... just found, could be hook\_enable() if I'm not mistaken about its usage

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


# Question
Title: How do I show content based on relationship?
There are two users A & B. A is in "friends" type relation with B. Basically what i want to achieve with this is that i want to display blog posts made by B (or any friends of A) to A. Now the content should be displayed inside a block on user A's profile page. (Just like facebook wall where you get latest updates from friends).

I know i can achieve this using Views but can anyone point me in correct direction?

User Relationships module is what i am presently using.

# Answer
> 1 votes
1. Create a new View with whatever fields, teasers that you want.
2. Click on the "Advanced" tab and that should open up a whole bunch of sections. You need the "Relationships" section. Click "Add". In the popup find "User Relationships: Requester user" that's your key.
3. Now you need to validate who that Requester is. You do it through the Contextual Filters. Click "Add" and find "User Relationships: Requester user", and inside it's options select "Current User".
4. Now you need to filter content that is written by "friends of" the current user. For that you need to add another relationship "User Relationships: Requestee user" which is a relationship of "User Relationships: Requester user" that you have already established.
5. Under "Filter Criteria" click "Add" - find "node Author", and in it's options choose "requestee".

These are the basic directions, you can play around with it under different combinations.

---
Tags: users
---


# Question
Title: How to capture credit card information to manually process later?
I developed a Drupal 7 website for a client who hosts a yearly fitness expo. This year he has a competition event that requires registration and a fee. I am looking for a way securely capture the necessary credit card and customer information to be used later to manually process the transaction.

My client has a Squareup account that he wants to use to process the transactions. I am open to other solutions as well. While I know what Square is, I don't know anything specifically about it. Does anyone know if they offer a way for me to link to a form on their site to do what I am looking for?

# Answer
Check out Commerce and Ubercart shopping carts. This is the right and best way to do this as it will save you the PCI headache as well.

However, seems that neither of the two do not have SqareUp payment integration, so you will have to do that yourself. You will have to read their API documentation and make appropriate custom module for integration.
> 0 votes

---
Tags: forms
---