title: Storing php query result into an array

text:
# Question
Title: Storing php query result into an array
How can I store php query result into an array in Computed field code(PHP)?

For example:

```
$query = db_query('SELECT field_holiday_date_value FROM field_data_field_holiday_date');

```

how can I store it into an array?

# Answer
> 4 votes
```
$result = $query->fetchAll();

```

This will store the records in $result as an array. You then need to store it in the computed field, which is something like this:

```
$entity_field[0]['value'] = $result;

```

References:

https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db\_query/7

https://drupal.org/node/126522

---
Tags: entities
---


title: How can I use drush dd in bash script?

text:
# Question
Title: How can I use drush dd in bash script?
In a bash script I use `drush site-set @foo_alias` to simplify subsequent drush commands.

I would like to compile my SaSS files using `compass compile $(drush dd my_theme)`. However, for this case I have to explicitly specify the alias as in `compass compile $(drush @foo_alias dd my_theme)`.

Otherwise, I get an error message:

> You need to specify an alias or run this command within a drupal site.
>
> Target 'my\_theme' not found.

Is there a bash syntax that obviates the need for the alias in the `drush dd` command?

# Answer
There are several ways to specify which Drupal site Drush will target; the alias is probably the simplest.

The second option is more verbose, but it does not require an alias file. Run:

```
$(drush --root=/path/to/drupal --uri=http://mysite.com dd my_theme)

```

You can do the same thing with a slightly different syntax:

```
$(drush /path/to/drupal#mysite.com dd my_theme)

```

You can also specify the Drupal site implicitly, by setting the cwd to the folder that contains the settings.php file for your site:

```
cd /path/to/drupal/sites/default # or /path/to/drupal/sites/mysite.com, as appropriate
$(drush dd my_theme)

```

A distant fourth option would be to use the site-set command; that would be a bad idea, though, as it uses the current process id to identify the filename that stores the current Drupal site. If your bash script created any subprocesses (e.g. by wrapping sections of the script in parenthesis, using $(), using backticks, etc.), then commands inside the subprocess will "forget" the currently set site.

For example, the following script will only print the site that was set once; the portion of the script inside parenthesis fails to find the set site:

```
drush site-set @foo_alias
echo "process $BASHPID"
drush ev 'return drush_sitealias_site_get();'
(
  echo "subprocess $BASHPID"
  drush ev 'return drush_sitealias_site_get();'
)

```

In a script, you are better off putting the site specification into a variable, and explicitly use that variable with every invocation of Drush.
> 3 votes

---
Tags: drush
---


# Question
Title: In Views, how do I get a link directly to an image file (not the node containing the image file)?
I have a view that displays nodes in *fields* format.

I have a *Global text* field in which I want to display the URL of images contained in nodes; however, I can't find how to get the URL of the images.

What I've tried:

* I added the Image field and chose "Content" as the option for "Link to." This is the link I want, but this prints out the image too (I don't need the image) and I can't use this field as a replacement pattern.
* I added a link to the content itself, but then this gives me a link to a node, not the image.

In Views, how do I get a link directly to an image file (not the node containing the image file)?

# Answer
> 3 votes
An option that doesn't require installing a new module:

* Create a Relationship to the image for which you want to create a link
* Add a field File:Path
* Exclude from display
* Rewrite Results - output this field as a link
* Add the replacement pattern to your global text

# Answer
> 1 votes
You have to use Image URL Formatter module.

This module provide a image formatter as Image URL.

Select That formater in views .

---
Tags: views, media
---


title: Flag a node programatically

text:
# Question
Title: Flag a node programatically
I am trying to get flag "purchase" and flag it for an user while completing an order in Rules (Commerce). This is how it goes in a PHP code:

```
$flag = flag_get_flag('purchase');
$nid = $_SERVER ['REQUEST_URI'];
$nid = explode("node/", $nid);
$node = node_load($nid[1]);
global $user;
$flag->flag('purchase', $node->nid, user_load($user->uid), TRUE);

```

Does anybody see any inaccuracy in what I've done? I just don't know why it is not working.

This is the error I am getting (actually it says nothing to me):

> Notice: Undefined offset: 1 in eval() (line 4 of C:\xampp\htdocs\mysite\sites\all\modules\rules\modules\php.eval.inc(146) : eval()'d code). Notice: Trying to get property of non-object in eval() (line 6 of C:\xampp\htdocs\mysite\sites\all\modules\rules\modules\php.eval.inc(146) : eval()'d code). Notice: Trying to get property of non-object in flag\_entity-\>applies\_to\_entity() (line 130 of C:\xampp\htdocs\mysite\sites\all\modules\flag\includes\flag\flag\_entity.inc).

# Answer
> 3 votes
Try below code... You can read node arguments using arg function in Drupal...

```
global $user;
$flag = flag_get_flag('purchase');
$node = node_load(arg(1));
$flag->flag('purchase', $node->nid, user_load($user->uid), TRUE);

```

---
Tags: commerce, flags
---


title: Progress bar based on role

text:
# Question
Title: Progress bar based on role
I am looking to creating a progress bar on which it is displayed how far you are between role 1 and role 20 (Role names: Level 1 - level 20)?

I take it I would have to use some php or javascript with a hook into the specific users role.

Any ideas on how to go about this?

Cheers,

# Answer
You can read user roles using below code...

```
global $user;
$user_roles = $user->roles;
$progress_value = x * 5; // where x is value extracted from $user_roles
if( is_numeric($progress_value) && $progress_value > 0 && $progress_value <= 100 ) {
  $style = "width: ".round($progress_value)."%; display: block";
}
print '<div id="progress-wrapper">
  <div id="progress-value" style="<?php print $style; ?>"></div>
<div>';

```

Now the solution needs some CSS to make it look like a progress bar. Start with a basic style - just a black border with a gray filling:

```
<style>
#progress-wrapper {
  border: 1px solid #000000;
  background-color: transparent;
  width: 100px;
  height: 16px;
}
#progress-value {
  background-color: #acacac;
  height: 16px;
}
</style>

```
> 0 votes

---
Tags: users
---


title: Issue with Disqus comments

text:
# Question
Title: Issue with Disqus comments
I seem to be having a difficult time getting the Disqus module to work on my Drupal website. Installation is normal, I just can't get to Disqus configuration page. The configuration page is blank.

I want to know: Does Disqus have any tables? If it does: Can someone give me the table structure, to see if I can use it?

# Answer
> 1 votes
Yes, the Disqus module has it own table (named `disqus`).

To see this table, look up the file `disqus.install` and examine the array called `$schema`.

You'll find this file inside the project directory (normally `sites/all/modules/disqus/`) where you installed Disqus, or in the project's git repo at *drupalcode.org*.

The Disqus schema is reproduced below for easy reference:

```
$schema['disqus'] = array(
  'fields' => array(
    'did' => array(
      'type' => 'serial',
      'not null' => TRUE,
     ),
     'nid' => array(
       'type' => 'int',
       'not null' => TRUE,
       'default' => 0,
     ),
     'status' => array(
       'type' => 'int',
       'unsigned' => TRUE,
       'size' => 'tiny',
       'not null' => TRUE,
       'default' => 0,
     ),
  ),
  'primary key' => array('did'),
  'indexes' => array(
    'nid' => array('nid'),
    'status' => array('status'),
  ),
);

```

---
Tags: comments
---


# Question
Title: Compine the author id's of two nodes in views and display block if equal
I know the title is really bad and not descriptive at all, but here is the case :

On a Drupal 7 site, each user has a "profile" page, which is a node of a certain content type, created upon registration (Content Type A). So far , so good. I want to let each user create nodes of a Content Type B, and display their preview on their "profile" page.

For Example, let's say each user is a musician and each user has a profile page presenting themselves with several blocks and views. The purpose is to let them create content concerning their gigs, and display the resulting block with the list of the upcoming gigs.

The problem is, that trying to create a view achieving it, i cannot use as a filter the ideal, which would be something in the form \[Content\_Type\_A\]\[nid\]\[authorid\] = \[Content\_Type\_B\]\[nid\]\[authorid\], so as to display the nodes of content type B that are created only by the same author.. I tried with contextual filters (author id), but this refers only to the node that is displayed in the view (in this case Content\_Type\_B), so, it has no result. Maybe it is something really really simple, but i'm stuck, since i have to declare the two types of nodes in the view in order to compare their author's ids.

Any help would be very useful.

# Answer
> 1 votes
I can't comment, so I'll answer instead. If I read your question correctly, you want to show multiple specific views on a specific content type which you have associated as a profile page.

You could do the following in each view:

* Create a relationship to the Author
* create each view as a block, using a contextual filter

+ (author) User:Name
    + When filter value not available: provide default, Raw value from URL, Path component 2
    + path users/%/view-name
* add it as a block in an appropriate place for your theme, and restrict it to show only on users/\* pages

I have done this to show recent blog entries in a profile page.

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


# Question
Title: how to pull data from view to file and attach to email
I have a particular use case where I want to be able to convert an existing list of Flags into a file and attach this to an email sent to the admin and user.

I currently have a working Flags list set up. What I would like to do is to covert this view to a file and be able to email it to my user and myself (admin) on the forms submission.

I envision implementing this through 1) creating the Flag list 2) converting to file 3) emailing this as an attachment to an email through the webform.

I've found modules that deal with data export, but I need some guidance on how to implement this. I suspect I may have to build my own module, but I'm only starting to dive into how to do this. Any advice on where to jump off would be greatly appreciated.

I imagine this will take the following steps: 1) check that flag list is populated 2) if flag list is populated write it to file 3) upon form submit, email a copy to user/admin

# Answer
1. You have to use Views PDF module to output of views as PDF.
2. Use Mime Mail module to send email with attachment.

Write own custom logic to action performed or any rules.

Custom function to send mail as attachment visit here.

You may also check this
> 0 votes

---
Tags: views, webforms, flags
---


# Question
Title: Combining the Same Terms in different Vocabulary as one
I have two vocabulary used by two different content type.

1. Category
2. Tags

However, the second content type does not use the Vocabulary Category. But there are nodes in second content type that has been tagged with same name in Category. So now I want to have the nodes of these same name be displayed as one.

That is Category has term - TermA Tags has term - Term A

Node of Type1 has been associated with TermA of Category and Node of Type2 has been tagged with TermA of Tags, but both these nodes should appear in one single taxonomy page as TermA. I am using Taxonomy Term Views.

How can this be done any ideas?

# Answer
You should try putting both Category and Tags under a single master vocabulary. Then assign both `Category` and `Tags` as parents of the shared term. So you have:

* Level 1: `MasterVocabulary`
* Level 2: `Category [parent:MasterVocabulary]`, `Tags [parent:MasterVocabulary]`
* Level 3: `SharedTermA [parents:Category, Tags]`, `TermB [parent:Category], ...`
> 2 votes

# Answer
While I'm not sure if it allows merging terms in different vocabularies, you could try

Term Merge

It allows merging terms via the admin taxonomy user interface.
> 0 votes

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


title: Views Error - Views folder is empty

text:
# Question
Title: Views Error - Views folder is empty
I have a drupal site on remote server. The site is working properly right now.

I just check and the views folder is empty!!

I looked into the ftp, and also on the remote server it looks like the views folder is empty. The site works perfect currently with many views, but it looks like the views folder under public\_html/sites/all/modules/views is empty.

When I checked the permission it say "0711". and it says that owner can read edit and everything..

How that can be that I see empty folder?

# Answer
The problem was that the views folder was on the ROOT/modules folder, and not on the ROOT/sites/all/modules folder.
> 0 votes

---
Tags: views, backups
---


title: Content locking module for Drupal 7

text:
# Question
Title: Content locking module for Drupal 7
Is there a stable module for content locking (anti-concurrent editing). I found this https://drupal.org/project/content\_lock but it's unsupported. Thanks

# Answer
> 3 votes
This is already built-in in Drupal 6 and 7, in the function node\_validate.

The relevant piece of code is reproduced below:

```
if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}

```

It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done. The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.

This warning message serves the same purpose as locking, but IMHO it does it better and less prone to deadlocks.

The problem with an outright lock is that users may open a node edit page but don't actually do any edits. If they just abandon it (i.e. don't press "Save") it will remain in that state until reset. Doing it on save is better because it avoids the deadlock situations that may arise from locking something the user may abandon.

---
Tags: nodes
---


title: Encrypt entire site - request access

text:
# Question
Title: Encrypt entire site - request access
How can I encrypt my entire site?

I also need to require password and username to access site. When visitors are accessing site, they will be redirected to a login page where they can also request membership. How to implement that?

# Answer
There is no built-in way to do two-way encryption in Drupal, but there are two modules that will extend Drupal to support encryption:

**Encrypt:**

* Includes multiple encryption methods from simple to complex depending on libraries available on the server.
* Focused on being a simple API that doesn't do much on its own.
* Sub-module Field Encrypt let you use it to encrypt fields *without* coding (but beta only, no stable release of this one).
* Uses **CTools** plugins for encryption methods and key providers.
* Contains unit tests for all the features.
* Stable Drupal 7 release, about 1400 installed sites.

**AES:**

* Includes support for one encryption method (AES).
* Built in functionality focused on two-way password encryption. Other uses requires coding by means of the API.
* Requires use of the PHP extension *mcrypt* or the *phpseclib* (PHP Secure Communications Library) external library.
* Has no built-in testing.
* Stable Drupal 7 release, about 3000 installed sites.

You should be able to encrypt the entire site by using either of these modules and create a simple custom module that uses the hook system to encrypt content before it is stored in the datebase and decrypt as part of rendering content.

You may even do it without creating a custom module by means of **Encrypt** with sub-module **Field Encrypt** \- if you find the beta-realese of the latter stable enough for your uses.

(PS: I can tell you how to restrict access as well, but that need to be a separate question).
> 1 votes

# Answer
If you need to encrypt images as well (I had to do this recently for passport photos attached to users accounts) then I found a solution using the Storage API module together with the encrypt module.

First set the image field's storage backend to be the database.

Then I had to modify the db.inc file included with the storage\_api module.

First change the `serviceInstanceCreate` function to add a line to encrypt the data before inserting into the DB.

```
public function serviceInstanceCreate(Storage $storage, $uri) {
  $active = $this->setActiveDB();

  $data = file_get_contents($uri);
  $data = encrypt($data);

  db_insert($this->settings['table'])
    ->fields(array(
      'file_id' => $storage->file_id,
      'contents' => $data,
      ))
    ->execute();

  return $storage->file_id;
}

```

And then in `serviceInstanceGetContents` check if the contents is encrypted, and if it is decrypt it.

```
public function serviceInstanceGetContents($reference) {
  $active = $this->setActiveDB();

  $contents = db_select($this->settings['table'])
    ->fields($this->settings['table'], array('contents'))
    ->condition('file_id', $reference)
    ->execute()
    ->fetchField();

  if ($contents === FALSE) {
    throw new StorageException();
  }

  // check if this is encrypted and decrypt if necessary
  $unserialized = unserialize($contents);
  if(is_array($unserialized)) $contents = decrypt($contents);

  return $contents;
}

```
> 0 votes

---
Tags: security
---


title: What drives the main menu?

text:
# Question
Title: What drives the main menu?
Hi I'm trying to understand the main menu but it appears to be self populating with the product categories category plus a built in search API (All Products). The main menu also appears disabled in the blocks area? Can someone explain the mechanics behind this menu please?

Well it looked like from Category\>Product category\>Edit vocabulary there is an option for Taxonomy menu with a selection list showing Main Menu. I added a new Category to this same structure and now both my new category and the main menu have disappeared from the menu? I have tried "Select to rebuild the menu on submit." and also removed my new category from main menu... but still the original is missing.

# Answer
You can see region--menu.tpl.php which is rendering main menu..

```
<div<?php print $attributes; ?>>   <div<?php print $content_attributes; ?>>
    <?php if ($main_menu || $secondary_menu): ?>
    <nav class="navigation">
      <div class="primary-menu inline">
        <?php print theme('links__system_main_menu', array('prefix' => '<div>', 'links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix', 'main-menu')), 'heading' => array('text' => t('Main menu'),'level' => 'h2','class' => array('element-invisible')))); ?>
      </div>
      <div class="second-menu inline">
        <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix', 'secondary-menu')), 'heading' => array('text' => t('Secondary menu'),'level' => 'h2','class' => array('element-invisible')))); ?>
      </div>
    </nav>
    <?php endif; ?>
    <?php print $content; ?>   </div> </div>

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to create a content type to embed video in drupal 6?
I want to create content type to embed videos.

When admin want to post an article which will have a video content then he will just provide the video link in the field and then automatically video will be get embedded into that article.

Currently I have created a new content type but there is no field type to embed video link.

How can I achieve it ?

# Answer
> 1 votes
You are looking for Embedded Media Field module. After enabling just paste the URL of the video, it will render the video on the page. It supports almost all the videos like youtube, vimeo, etc..

> This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.

---
Tags: files, nodes
---


# Question
Title: How to fetch a single value with an entity metadata wrapper?
Say I want to fetch a single value from the node table: I could use the database API:

```
$value = db_query('
  SELECT title FROM {node} WHERE nid = :nid
', array(':nid' => $nid,))->fetchField();

```

What is the equivalent using an entity metadata wrapper?

Thanks.

# Answer
> 0 votes
Well you could use:

```
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$title = $wrapper->title->value();

```

But if that's literally all you need to get from the node, an `EntityMetadataWrapper` is overkill in my opinion. Just use:

```
$node = node_load($nid);
$title = $node->title;

```

---
Tags: entities
---


# Question
Title: How to save database connection easy and safe?
I'm trying to let Drupal7 connect to several databases(pgsql) and update data automatically. So I use `Database::addConnectionInfo($name,'default',$connString)` And `db_set_active($name)`.

It works perfectly until I realize it's dangerous to save database password in fields while the connection string actually needs it.

Is there any way to do so easy and safe?

Thank you! :)

# Answer
Well, there is the encrypt module which can encrypt your data. Be sure to use the 7.x-2.x branch.

And yes, store the key somewhere on the filesystem that is not easily accessed and it should be hard for an attacker who has db access to be able to decrypt the info.

Just be sure that there's no way to execute php via the Drupal interface. A module like paranoia can help in that.
> 1 votes

---
Tags: 7, database, security
---


# Question
Title: get all nodes created in a specific month
I have a custom search form that I posts a year + month, such as 2014-04 I would like to get all nodes created that month, when I create the timestmap I use: "SELECT ....... AND `changed` \>= 'strtotime($date)'"

This is the code for form date:

```
$form['aqar_date'] = array(
'#type' => 'date_select',
'#title' => t('Date'),
'#prefix' => '<div id="space_replace" class="search-title-date">   <h2>Node date</h2>',
'#suffix' => '</div>',
'#date_format' => 'Y-m',
'#default_value' => date('Y-m'),
'#date_year_range' => '-4:+0',
);

```

This is the form submit:

```
$start_date = strtotime($date);
$query = "
SELECT `nid` FROM `node`
WHERE
`type` = 'custom'
 AND `changed` >= '$start_date'";

```

But I'm not getting, I need a way to specify to only this month period not this month and newer!

Thanks!

# Answer
Here you go with the code.. I have used entity field query to retrieve results.. Code should be self explanatory.. Let me know if you have any difficulty in understanding below code..

```
<?php

$year_month = "2014-04";
$date = date_parse_from_format ("Y-m" ,  $year_month);
$num = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
$first_minute = mktime(0, 0, 0, $date['month'], 1, $date['year']);
$last_minute = mktime(23, 59, 59, $date['month'], $num, $date['year']);
$entity_type = 'node';
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', $entity_type);
$efq->propertyCondition('created', array($first_minute, $last_minute), 'BETWEEN');
$result = $efq->execute();
dpm($result);

?>

```
> 6 votes

---
Tags: database
---


# Question
Title: Search form directs to main site from sub-domain
I have a sub-domain setup with a default main domain (or dual sub-domain if you prefer): www.example.com and m.example.com (mobile). I am using Drupal 7.27. I am using Themekey 7.x-3.0 for theme switching which is working, but I'm not sure if that is what's causing the problem. If I enter a search parameter under a form created on m.example.com, the form submit is redirected to www.example.com to handle the search page, meaning the theme is switched back. I checked the output, and the form search action = /, and when I use that (as a test) in a link or other reference, it lands on m.example.com as it should. Does anyone know what might be causing this?, is this default functionality?, and what I could do to prevent it or override it?
I don't have any other redirect modules, or Rules setup that should be redirecting. Any help or direction would be greatly appreciated. Thanks.

# Answer
Thanks to harshal:

The problem ended up being a lack of a distinct settings.php for the sub-domain. \- I created the folder under sites for the sub-domain \- copied and modified the default settings.php with the correct base\_url

This created a new problem whereby the sub-domain was looking for files under the wrong folder (they were under the default folder) \- I adjusted the settings in admin/config/media/file-system for Public to sites/files (universally accessible) \- copied all files over
> 1 votes

---
Tags: search, subsites
---


# Question
Title: Hiding sections of text for certain users
In my drupal site on certain pages I want to hide certain links or bits of text in the body field for particular roles.. I might want to do something like

either

```
hide this text for custom_role_1 but show it for all other users

```

or something like

```
switch
 case role = anon, then print this text
 case role = custom_role_1, then print this text
 case role = custom_role_2, then print this text

```

now I know I could achieve this using field\_permissions and just create a field for each role type - but that feels like overkill... as it's only a few times I'll be needing this.. what I'm thinking is, is there a bit of php someone could show me that I could just stick in there instead? I could switch from editing those pages from using the wysiwyg to the php-input edit mode???

# Answer
Aside from field permissions, you could make sure that the information you want to hide is separated from the rest of the content in its own block and restrict the ability to view it to certain roles, which is essentially what it appears you want to do, only not in php.
> 2 votes

---
Tags: users
---


# Question
Title: CSS not loading on Chrome for drupal site after moving to https
I have a Drupal site which has huge content. Recently I moved my dev content on production and also changed the site URL from http to https.
The problem is that the site is working fine on all browser except Google Chrome. It is not loading the CSS. I can see the content but its without CSS.

I have the same setup for dev site and production site but still it is not showing any css.
If anybody has a solution please let me know.

Also I am using the same theme for dev and production.
In the site information it is showing the following message:

> This page includes other resources which are not secure.

# Answer
The warning which you see is because some of the contents are not secure, which means they are fetched using `http` instead of `https`.
As per the limited information provided by you, I'd suggest you to follow the following steps:

* Inspect the source code of the page, by pressing `CTRL` \+ `U`, in Chrome.
* Check to see if there are links present in the content(specially the `<head>` section) are using the pattern `http://...` instead of `https`.
* Find the resources (css/js/images) which are loaded using `http`.
* Identify which part of the site (module or a theme function) adds that resource.
* Make the necessary changes to make sure the resources are loaded securely i.e. via `https`.
> 2 votes

# Answer
One possible answer is that you have your `$base_url` in settings.php set to something like `http://www.example.com`. Try commenting out that line or changing `http://` to `https://`.
> 2 votes

---
Tags: migrations
---


# Question
Title: showing taxonomy (tags) in alphabetical order on nodes
I just noticed that my tags are appearing at the bottom of my posts in the order I entered them, not in alphabetical order. I'm sure this is something simple, but I can't figure out how to get them to display on my nodes in alphabetical order.

# Answer
The first thing that comes to mind, you can try to reorder taxonomy tags in vocabulary in alphabetical order. Perhaps there is a better solution...
> 0 votes

# Answer
Well, this will work but it does seem rather complex for what we are trying to achieve:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {

  switch ($node->type) {

    case 'article': // Replace with your content type.

        $tags = array();
        // Loop over values.
        foreach($node->content['field_tags'] as $k => $v) { // Replace your field name.
            // We only want the ones with numeric keys (that actually contain tags)
            if(is_numeric($k)) {
                // Add this to the $tag array using the name as a key.
                $tags[$v['#title']] = $v;
                // Unset from the content array.
                unset($node->content['field_tags'][$k]);
            }
        }
        // Now sort by the array keys.
        sort($tags, SORT_STRING);
        // And add back into the content array.
        $node->content['field_tags'] = array_merge($node->content['field_tags'], $tags);

        // Phew!

        break;
  }

}

```
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: exclude contextual filters from breadcrumb
I'm having a bit of a problem here. I have a view which contains a list of items. At the top there are some vocabulary terms which you can click. When you click you go to a next page which shows a filtered list.

The problem is, on that new page, the filters are being added to the breadcrumb which I don't want. How can I exclude these filters from the breadcrumb?

example The page with the complete list has this breadcrumb, which is good: Home » Opleidingen » Bijscholing

Next, if we click on 'gasten, hoe gaan we er mee om', the list gets filtered with the word 'gasten', on the next page the breadcrumb is like this: Home » Opleidingen » Bijscholing » Gasten, hoe gaan we ermee om? » » gasten » gasten

I want to be able to exclude this part '» » gasten » gasten'

# Answer
Click the "override breadcrumb" box in the settings pane for the contextual filter. You can override it with a custom value and you can use `%1`, `%2`. This won't exclude them but it will clean up the problem of the repeated words.
> 2 votes

# Answer
To remove the breadcrumb from a view when using a contextual filter:
> 2 votes

# Answer
Here is solution:

```
/**
 * Implements hook_preprocess_page().
 */
function MODULE_preprocess_page(&$variables) {
  $page = menu_get_item();

  if (($page['page_callback'] == 'views_page') && ($page['page_arguments'][0] == VIEW_NAME)) {

    // Remove breadcrumbs from view arguments.
    $breadcrumb = array_slice(drupal_get_breadcrumb(), 0, 1);
    drupal_set_breadcrumb($breadcrumb);
  }
}

```

This code removes all items from breadcrumb except Home link, and if you theme add current page to breadcrumb - you will see "Home \> View name". If not - just change parameters in array\_slice fucntion.
> 1 votes

# Answer
You can customize the breadcrumb from contextual filter.
> 0 votes

---
Tags: 7, views, breadcrumbs
---


# Question
Title: Ideas for implementing a shift scheduler? calendar? custom content type?
for our NPO we need the following feature: We have a bar, hotel and restaurant, and there are some fixed shifts ie. 7am to 12am, 12am to 7pm and so on, the whole week;

* People enter their wanted work shift themselves;
* There has to be an overview what shifts are set and which ones miss workers. A table for the current and next week, coloured with the user names;

I thought about a custom content type in a module, where the time (start, end) are set by the admin and can be changed from time to time. On click in the calendar resp. the overview panel, the node is prepopulated with auto\_title and the times and the entityreference to the user.

And ideas if there is a view plugin which could do the overview, or do i need to code that myself?

I am aware of : shift\_scheduler module (sandbox)

# Answer
Maybe you are aware of the calendar module https://drupal.org/project/calendar It has a very nice integration with views, and you could create a calender from template for a specific content type that has date fields in seconds (that generates also a view of it per week). Of course for the case you have described you will need custom coding, surely the Drupal Ajax Framework and some other stuff... but that sounds more like fun :)
> 0 votes

---
Tags: nodes, datetime
---


title: Drupal search based on content type

text:
# Question
Title: Drupal search based on content type
I have two type of content lets say News and Article. Now, I want search over these two content types(option is given to user). I am using default search module of drupal. I am able to search both by www.example.com/search/node/ but unable to filter out because I don't know how to provide content type here.

My question is :

How to provide search parameters (like content type) to URL so that my search works correctly according to content type?

I try to provide www.example.com/search/node/\[content type\]/\[search pattern\] then "\[content type\]/\[search pattern\]" become actual search pattern. What are the options I have.

If URL change is not the solution what are the options I have to resolve the issue.

Regards, Yatendra.

# Answer
You could make the same search with a view and add contextual filter to achieve the specific URL pattern and normal field filters to apply other filtration if needed. The view could render the node with the same display that you was going to use for the default search so if you have already built the markup - you don't have to do it again.

Edit: Also if you want to use the default search api - you could make a facet to filter with the help of the Facet API Module
> 0 votes

---
Tags: nodes, search
---


# Question
Title: Is there anyway to show all results in a view initially, but only show 1 result after user sets an exposed filter?
I need to be able to show all results of my view initially but then only show 1 result after the user selects their options form the exposed filters.

# Answer
> 0 votes
For the record, this seems like a really odd thing to want to do! How would you narrow it down to a single result if more than one matches the filter?

Anyway, you should be able to use this hook: https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7

If you check for the existence of filter values, you can then apply a "LIMIT 1" to the query.

---
Tags: views
---


# Question
Title: Change field type with hook_update_n for a module
Hello I need to update the field type of one of my content types. The content type is of a module so I need to do this with the Drupal API for let users update the module for their 7.x-1.0 branch.

This is the hook for update the field, I need to change it from Integer to Decimal like this:

```
 /**
 * Change field_inq_description field from Integer to Decimal
 */
function field_updates_update_7100() {
  // Manual database changes.
  db_query("UPDATE {field_config} SET type = 'number_decimal' WHERE field_name = 'field_rin'");
  db_change_field('field_data_field_rin', 'field_rin_value', 'field_rin_value', array(
    'type' => 'numeric',
    'precision' => '10',
    'scale' => '2',
  ));
  db_change_field('field_revision_field_rin', 'field_rin_value', 'field_rin_value', array(
    'type' => 'numeric',
    'precision' => '10',
    'scale' => '2',
  ));
  // Clear caches.
  field_cache_clear(TRUE);
  // Apply the new field instance configuration.
}

```

After I apply the update with update.php script I get these notices everywhere in the test website.

```
Notice: Undefined index: precision in number_field_schema() (line 35 of /home/servilla/public_html/servillantasgiraldo.com.co/modules/field/modules/number/number.install).
Notice: Undefined index: scale in number_field_schema() (line 36 of /home/servilla/public_html/servillantasgiraldo.com.co/modules/field/modules/number/number.install).

```

What Im I doing wrong?

# Answer
> 0 votes
I found the answer, the help of Clive was great. Look this is the final code:

```
/**
 * Change field_inq_description field from Integer to Decimal
 */
function field_updates_update_7104() {
  // Manual database changes.
  db_query("UPDATE {field_config} SET type = 'number_decimal' WHERE field_name = 'field_rin'");
  db_change_field('field_data_field_rin', 'field_rin_value', 'field_rin_value', array(
    'type' => 'numeric',
    'precision' => '10',
    'scale' => '2',
  ));
  db_change_field('field_revision_field_rin', 'field_rin_value', 'field_rin_value', array(
    'type' => 'numeric',
    'precision' => '10',
    'scale' => '2',
  ));

    // Doing it with the raw way is the best choice.
    $data = unserialize(db_query("SELECT data FROM {field_config} WHERE field_name = 'field_rin'")->fetchField());
    $data['settings']['precision'] = 10;
    $data['settings']['scale'] = 2;

    db_update('field_config')
    ->fields(array('data' => serialize($data)))
    ->condition('field_name', 'field_rin')
    ->execute();

  // Clear caches.
  field_cache_clear(TRUE);

```

If you do it with the API way clive suggested and if you already have nodes of that content type the update.php script will show you an sql error telling you that you cannot update field properties with existing data, So the raw way clive suggested is the best way for do it. Thanks to Clive

# Answer
> 3 votes
You just need to add `precision` and `scale` to the field config settings:

```
// API way.
$field = field_info_field('field_rin');
$field['settings']['precision'] = 10;
$field['settings']['scale'] = 2;
field_update_field($field);

// Raw way (shorthand, you'll want to add error checking).
$data = unserialize(db_query("SELECT data FROM {field_config} WHERE field_name = 'field_rin'")->fetchField());
$data['settings']['precision'] = 10;
$data['settings']['scale'] = 2;

db_update('field_config')
  ->fields(array('data' => serialize($data)))
  ->condition('field_name', 'field_rin')
  ->execute();

```

---
Tags: 7, entities, updating
---


title: Converting from a WordPress theme

text:
# Question
Title: Converting from a WordPress theme
I'm converting a WordPress theme. And, yes, I'm following the very good advice listed in a previous question. My question is more granular. So hence, this new question.

Specifically, I'd like to address the menu creation. Should I use the typical theme() functions to build out Main and Secondary menus? What class names should I pass into that theme function?

Currently, I've cleaned up the HTML template by extracting all embedded JS and CSS into external files. It appears as

```
<div id="navigation" class="ten columns clearfix">
    <div class="menu-navigation-menu-container">
        <ul id="nav" class="menu">
            <li id="menu-item-2691" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-419 current_page_item menu-item-2691">
                <a title="home" href="new_design_staging.1.html">home</a>
            </li>
            <li id="menu-item-2565" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-2565"><a href="new_design_staging.1#">about</a>
                <ul class="sub-menu">
                    <li id="menu-item-2571" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2571"><a href="new_design_staging.1#">Drop Down 1</a></li>
                    <li id="menu-item-2572" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2572"><a href="new_design_staging.1#">Drop Down 2</a></li>
                    <li id="menu-item-2573" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2573"><a href="new_design_staging.1#">Drop Down 3</a></li>
                </ul>
            </li>
            <li id="menu-item-2566" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2566"><a href="new_design_staging.1#">books</a></li>
            <li id="menu-item-2567" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2567"><a href="new_design_staging.1#">movies</a></li>
            <li id="menu-item-2568" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2568"><a href="new_design_staging.1#">time travel</a></li>
            <li id="menu-item-2569" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2569"><a href="new_design_staging.1#">blue box</a></li>
            <li id="menu-item-2570" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-2570"><a href="new_design_staging.1#">boats</a></li>
        </ul>
    </div>
</div>

```

Or, can I loop over a render variable to produce the `<li>`, leaving the `<div>` and `<ul>`'s in place? Does this deviate too far from best practice?

# Answer
> 1 votes
Well, here is the code that I've put in place. So far it's respecting the CSS selector patterns that the WordPress theme rendered.

```
<div id="navigation" class="ten columns clearfix">
    <div class="menu-navigation-menu-container">
       <?php
       print theme('links__system_main_menu', array(
         'links' => $main_menu,
         'attributes' => array(
           'id' => 'nav',
           'class' => array('menu')),
         'heading' => t(''))
       );
       ?>
    </div>
</div>

```

---
Tags: theming
---


# Question
Title: How do I show/hide elements on a page using jquery?
I am trying to hide check-box selectors in the custom search module when the page initially loads and then have a clickable link to show them. I have the clickable link working but the check-boxes are initially in a visible state. How can I hide the check boxes when the page/module loads? I tried placing the following code in my THEME\_form\_alter(&$form, &$form\_state, $form\_id) function

```
drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types")[0].hide(); });', 'inline');

```

and

```
drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types").hide(); });', 'inline');

```

But neither worked. Any help would be appreciated. thanks

# Answer
> -2 votes
For Drupal 7

```
drupal_add_js('(function ($) { $("#edit-custom-search-types").hide(); }(jQuery));', 'inline');

```

Working with JavaScript and jQuery

# Answer
> 0 votes
the easiest way of adding custom javascript-snippets is to create a custom.js file in your themefolder and declare it in your theme.info file like scripts\[\] = custom.js. Add all your snippets there.

In your JS file you can hide the elements. If you have multiple checkboxes create an array and hide them with a for each loop.

example

```
// create array with stuff you want to hide
    checkboxes = [
        '#checkbox1',
        '#checkbox2',
    ];

// Hide arrays
    for (i = 0; i < checkboxes.length; i++) {
        jQuery(checkboxes[i]).hide();
    }

```

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


title: Where do I put PHP to get a term ID?

text:
# Question
Title: Where do I put PHP to get a term ID?
I've been trying to figure our how to get a term ID of a taxonomy term I created, and I found a little bit of php that looks like it should work. However I have no idea where to put it to get a response.

I'm working on a D6 site that needed updating and already found this script

```
$term = taxonomy_get_term($tid);
$name = $term->name;

```

Any pointers?

# Answer
> 1 votes
That code won't work. The first line is using the `$tid` to load the term, obviously that won't work if you don't know the Term ID in the first place.

You don't need to use any PHP to get a taxonomy terms ID. Just goto the edit page of that term and look at the url. It will be `/taxonomy/term/TID/edit`

---
Tags: 6, taxonomy-terms
---


title: gallery colorbox thumbnail issue

text:
# Question
Title: gallery colorbox thumbnail issue
I've created an image gallery with colorbox and views like this tutorial. First image of the album is a thumbnail the others are content. So I want to display the thumbnail, when I click the thumbnail only show the other pictures except the thumbnail.

http://www.wdtutorials.com/2013/03/06/drupal-7-tutorial-how-create-image-overlays-colorbox#.U2Eyi\_l\_v94

I'v followed this tutorial excactly.

So far so good, but when I click my thumbnail the colorbox opens and shows my thumbnail and all the other images. The settings are the same as the video.

I have set the first image field the multi row settings display 1 item start 0 2nd image show all the other images and display all start 1

Can someone help me to solve my problem?

# Answer
> 0 votes
The colorbox module have given me a lot of headaches in the past. Shadowbox offers that functionality out of the box (and it looks a lot nicer without the hassle of theming it. https://drupal.org/project/shadowbox. I use version 4 myself on this site, see for an example how it looks: Click on the photo

---
Tags: views, media, javascript
---


# Question
Title: Zero pad Drupal 7 Form API Date Control day and month HTML select element
I'm using the Form API Date controls for my form, and I am wondering if there is a way to zero pad the month and day values in the HTML select elements for values less than 10 at declaration time. I am using the following render array declarations in the page callback function.

```
$form = array();

$form['date_from'] = array(
    '#title' => t('Date From'),
    '#type' => 'date',
);

$form['date_to'] = array(
    '#title' => t('Date To'),
    '#type' => 'date',
);

```

Which displays on the page as:

And creates the select element values (without zero padding):

# Answer
I think you can use #date\_format

```
  $format = 'm d Y';
  $form['date_from'] = array(
     '#type' => 'date',
     '#title' => t('select a date'),
     '#date_format' => $format,
   );

```

More values: http://php.net/manual/en/function.date.php
> 0 votes

---
Tags: forms, datetime
---


# Question
Title: Show node in overlay using drupal 7 overlay module
Is there anyway to open a overlay with a node content using drupal overlay core module? If I could reuse at least the javascript code I'd already be happy =)

# Answer
The faster way is to implement hook\_admin\_paths\_alter() in a module to redefine which of the menu items defined in `hook_menu()` by other modules are administrative paths. The value returned from the implementations of hook\_admin\_paths(), which are then altered from the implementations of `hook_admin_paths_alter()`, are used from the Overlay module to decide which pages are rendered as overlay. As other modules could use the same information to render the pages using a different theme, the module should require the Overlay module as dependency, to be sure the additional pages are effectively rendered as overlay.

```
function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*/view'] = TRUE;
}

```

If you notice that this implementation doesn't work when the users are viewing, for example,example.com/node/1, but only when they are viewing example.com/node/1/view, then I would implement the hook using the following code. The first implementation I provided should work, as the "View" tab is the default one, and when users are viewing example.com/node/1, Drupal is really showing example.com/node/1/view.

```
function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*'] = TRUE;
  $paths['node/*/view'] = TRUE;
}

```

As the first line could catch all the node pages (I didn't verify that), I would verify if there are other pages under that path that should not be rendered; in that case the implementation can be changed as the following one ("node/\*/backlinks" is only an example):

```
function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*'] = TRUE;
  $paths['node/*/view'] = TRUE;
  $paths['node/*/backlinks'] = FALSE;
}

```
* Normally, modules implement `hook_admin_paths()` to report which of their menu items are administrative pages; this means that if a page is not an administrative page, an entry for that page is not added to the returned array.
* `hook_admin_paths()` is implemented for the menu items defined in your own module; to redefine when menu items defined from other modules are administrative pages, you need to implement `hook_admin_paths_alter()`.
* To the pages that are defined as administrative pages is not automatically applied an access control; this means that the module defining those menu items that are reported to be administrative pages still need to use "access callback" and "access arguments" to define which users can access those menu items associated with administrative pages. Pages defined as administrative pages are only rendered differently, if there is a module that does that.
* The node module defines the node editing pages as administrative page only when a checkbox in an administrative page is selected; those pages are already handled.
> 6 votes

# Answer
You can also use the Overlay Paths module. This is a simple module that enables administrators to use the built-in Overlay for non-admin pages. This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.
> 6 votes

# Answer
I ended up using the Overlay Paths module with Panels so I could show our newsletter signup form. The form showed up, but it also included everything else on the page (header, footer, sidebars, etc.). It was displaying the newsletter signup page through the default site template.

So the tricky solution was to create a Variant on the default site template under Panels. The Variant was selected only if the Node:Type was a Webform. Then I removed the excess content and made the Variant display only the Main Content.

Presto! The newsletter signup page appeared in an overlay simply as a form that I could style to my CSS heart's content!
> 1 votes

---
Tags: 7, javascript, modal-dialogs
---


# Question
Title: Is it possible to style a Views 'group by' field that's excluded from display?
I'm working on a glossary view. I have created letter headers by rewriting a copy of the term title, limiting it to 1 character, excluding it from display, and using that as the "Group By" field. The field is then shown by Views, but it doesn't contain the `<h2>` tag that I wrapped around the field in the rewrite rules. The normal term titles are output (by default) with `<h3>` tags. I would like the letter headers to be larger, but since Views seems to be overriding everything, I can't see how to do accomplish this. It doesn't even output the class name I attached to the field.

Any ideas? Your help is appreciated!

# Answer
Under the advanced tab you can see what templates you need to override the views template. Copy the templates mentioned from the modules/views/themes folder to you own theme/templates folder, rename them as the view suggests under advanced and style your output.

note: if you display a teaser or full node, but forced it to use fields, the styling (making it h3) won't work.

The h3 is coded in views-view-unformatted-list.tpl.php. The $title there is output of the field you grouped by. There you can set it to h2.

UPDATE: This is the default views template for outputting lists (the container which contains all rows as a group). This one is named views-view-unformatted.tpl.php, you need to rename it to match with your view.

```
 <?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3> // THIS IS THE GROUPNAME
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?> // THESE ARE THE ROWS INSIDE THE GROUP
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

If you want to put style on ALL the rows inside the group then you can use the view-ui itself, or use the template called views-view-fields.tpl.php to override all rows.

If you want to style ONE specific row use views-view-field.tpl.php (note there is no 's' behind field).
> 1 votes

---
Tags: theming, views
---


# Question
Title: How to hide menu settings at content creation for specific content types
I'm adding menu items programatically. Is it possible to get rid of this for specific content types?:

In my situation it's just one more way to break something, and is totally not needed :) .

# Answer
> 1 votes
You can use `hook_form_alter` placed in a custom module or in your theme's `template.php` file for this. Try something like this:

```
function THEME_OR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  // There's probably an easier way to check if it's an update or create form.
  if (!$form['nid']['#value'] && $form['type']['#value'] == 'page') {
    unset($form['menu']);
  }
}

```

I'm not completely sure about the `$form['type']['#value']` value. You might want to double check that so you won't get any false positives on other pages which also has forms. You could use `$form_id` for this, but that variable is unique for each content type.

# Answer
> 1 votes
I tried to hide this menu as well. However hampusn's solution does not work form me. The way I achive it is down there, in case someone does experience same problem.

```
$form['additional_settings']['#access'] = FALSE;

```

Placed in hook\_form\_alter as suggested by hampusn. Make sure to use "#access"

---
Tags: 7, routes
---


title: Links not working on migrated site

text:
# Question
Title: Links not working on migrated site
I moved a site from a hosted server to my local machine and none of the links that point to internal pages work even though they look correct. I'm getting odd behaviour as described below. This is true even for the admin toolbar provided by the module (People, Modules, Configuration, etc.)

My process was as usual, I copied all the files down, exported/dumped the database, created a local db and then imported the dump.

(I'm putting in lh instead of localhost bec stackexchange won't allow links with localhost) I was able to login via lh/myidols5/?q=user but not lh/myidols5/user which gives 'access denied'. From lh/myidols5/?q=user, if I click on any link say the home button in the admin toolbar I go to the right page but am logged out. The address bar says lh/myidols5/ which is correct so I'm at a loss as to why I'm logged out.

Anyone know what the issue is?

Thanks

# Answer
I feel you're missing .htaccess file. Usually its a hidden file, so make sure to show all files (including hidden files) and copy it and paste it into your local drupal folder.

Also, make sure you local server has `mod_rewrite` enabled to support clean URLs, if its not enabled then check this answer: How to enable mod\_rewrite in Apache?.

Another suggestion is; to turn off Clean URL from `settings.php` by adding the following code:

```
$conf['clean_url'] = 0;

```
> 3 votes

---
Tags: 7, navigation, migrations
---


# Question
Title: Link field to node content only with Colorbox
I would like to show all "content type A" pop up in Colorbox, with "main content" only. Meaning no header, sidebar or footer.

So In my Drupal 7, I installed Colorbox and Colorbox node modules. And created a Views that list all of the "content type A". Then I added a "Content: Title" field with "link this field to the original piece of content" and "display the content inside of a colorbox" are checked. However, the link did pop up with colorbox but it come with full page, which is including the header, menus, footer and everything else. How can I just show the main content?

# Answer
> 3 votes
Go to admin/config/media/colorbox and at the bottom there is a settings called 'Colorbox Node Integration' **uncheck** `Enable Regions` and save it. After that colorbox shows only main content of node.

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


# Question
Title: How to get all filters and functions available in Twig templates?
I have an option to create and edit twig templates via UI but I need to display what filters and functions are available to the user but I don't know how to get them.

# Answer
From procedural code:

```
\Drupal::service('twig')->getFilters();
\Drupal::service('twig')->getFunctions();

```

Unless the Twig service is overridden this is calling the methods on the vendor `Twig_Environment` class.

For OO code you should inject the Twig service into your class. https://drupal.org/node/2133171 and https://drupal.org/node/2203931 have some documentation and examples on how to do that.
> 3 votes

---
Tags: 8, theming
---


# Question
Title: How to Modify Drupal 7 Bootstrap Theme Title?
I cannot find where to modify the title from:

**SiteName | SiteSlogan**

to

**SiteName - SiteSlogan**

I am using the https://drupal.org/project/bootstrap theme.

Anyone have any ideas?

# Answer
This thing is come under $head\_title variable on html.tpl.php.

So for changing this you need to override template\_preprocess\_html

where replace statement

`$variables['head_title'] = implode(' | ', $head_title);`

with

`$variables['head_title'] = implode(' - ', $head_title);`

I am assuming you have enough idea about overriding of templates.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How do I override the content region for a specific page?
I want to override the content region for a specific page, but using the hook `page--mypage--region--content.tpl.php` won't work. How should I name it?

My site supports block override, I tested this with a dummy `region.tpl.php` and I currently use a custom `page.tpl.php`.

# Answer
> 0 votes
For this you have to override preprocess region

```
function MYTHEME_preprocess_region(&$variables) {
    if(CONDITION){
        $variables['theme_hook_suggestions'][] = 'regionspecial__' . $variables['region'];
    }
    print_r($variables['theme_hook_suggestions']); // comment this statement
}

```

After that your template suggestion name will be 'regionspecial--content.tpl.php' For certain desired condition. Once you clear Drupal's caches your new template file should start being used for that region. It might be worth noting that you'll probably need a copy of the core region.tpl.php file somewhere in your theme folder as well, or the theme registry might not pick up your custom file.

---
Tags: theming
---


# Question
Title: reference an entity outside of the node/add or node/edit forms
I will explain you with my use case:

I have a content type "job post" and another content type "Exam" For apply to a job you must pass the exam, the "job post" content type has an entity reference field "field\_exam" that is referencing the "Exam".

While user creates the "job post" he can create his own "Exam" or he can Call for tender on creation of an "exam" for the "job post". In that case the User will recieve "exams" of other users and he will choose one of them for his "job post".

The list of options is a view of "exams", in front of the title of each "exam" should be a link that says "Choose this Exam", and if I click that link the field "field\_exam" of the "job post" must be referencing that "exam".

So the main point of this is, how to change update the "field\_exam" value selecting the entity outside, for example in a view or in the node page...

Thanks for your help.

# Answer
> 1 votes
You could use the Views and Rules Link modules (along with the Rules module) to accomplish this.

What you would do is create a Rules Link that will attach your line item (exam) to a Job (that the user selects).

You would likely need to have an field available for Rules to manipulate, but there would be no forms involved directly using an Entity Reference field (no forms involved).

---
Tags: 7, entities
---


title: omega where to make changes?

text:
# Question
Title: omega where to make changes?
I've installed Omega 7.x-4.2 and created my subtheme and I just want to start practising making changes with page.tpl.php and css but there are just so many files and so far nothing has affected change.

I copied over page.tpl.php found in omega/system folder and placed it in my subtheme/templates then placed styles in my subtheme/css/subtheme.hacks.css but see no changes at all.

Also have noticed in sites/all/themes the path structure is different for omega that is all/themes/omega/(ohm)omega/templates and in other all/themes/subtheme/templates. I set this up a while ago following documentation and can't remember why it has ended up this way and whether or not that would cause problems. There are no errors just no changes taking effect.

Just all seems so unnecessarily complicated!

# Answer
Omega 4 is essentially built around using SASS for styling. It's not a requirement, but the starterkit almost assumes it.

Assuming you have created a proper subtheme from the starterkit, you should have a directory called "sass". These are the files you would change. Peruse the README.md that is in there. A basic SASS file structure for partials is set up, and I find that it maps fairly well to Drupal. Each subdirectory also has a README.md. Nothing forces you to use this structure for your partials, but I like it.

After this, you need a working SASS environment. Everything should be there to get bundler going to install the gems you need. Personally, I move all of the SASS and other build files out of the theme, and to my project root folder. Then I have a single Gruntfile for making and deploying my project.
> 1 votes

# Answer
A couple of things you can check...

* In your subtheme, have you declared omega as your base theme in the .info file?

> ```
> name = omega sub theme
> description = my sub theme
> base theme = omega
>
> ```

* Have you enabled your subtheme as the default theme in admin/appearance?
* Have you flushed the cache after making changes? ( configuration \> development \> performance \> clear cache )
* In dev tools, or whatever you use to inspect an element, when you have the source open, what is the path? Is it definitely coming from your sub theme folder?
> 1 votes

# Answer
A SASS environment is not a strict requirement for writing CSS in Omega. It has provision for directly editing CSS. SASS makes things a lot easier.

Have you added your CSS file in the theme's info file? Did you clear the cache after that?

Don't follow Ohm(the sample theme which ships with Omega 4) as a standard. It is bleeding edge and not recommended for production use.

If you create the subtheme using the drush subtheme wizard command(drush owiz), it will create a subtheme with sensible defaults which is easier to get started with.
> 1 votes

---
Tags: theming
---


# Question
Title: How to trigger a popup window/overlay in my module?
I am stuck in my project. I am working on a module for account management page. When the user update their billing address, a service call will be triggered to send request to a third party API to get a response indicating if the address if valid or not. If valid then display the returned normalized address in a popup box or overlay, the user can choose if he want to use that address or not. My question is that how to trigger displaying this popup box in php code?

Thanks!

# Answer
Take a look at the Colorbox module.

You can find a few examples here.

Usage Example:

```
<a class="colorbox-load" href="http://example.com/?width=950&height=500&iframe=true">open URL in Colorbox (iframe)</a>

```
> 0 votes

---
Tags: modal-dialogs
---


# Question
Title: Avoid duplicate hits in two separate Views
I'm using Views to generate a number of lists, e.g. Newest articles and Popular articles. Now, often newest articles will also be in the Popular articles list.

So when I'm using both views on frontage, I would like to prevent, that the same article is shown on both lists.

So basically skip articles in Popular list, if they also are available on Newest list.

# Answer
This is not trivial to accomplish, and will in most cases require coding.

First of all, it's necessary to determine in which order the lists should be evaluated. One of them needs to take priority. The gist of the solution, is that in some way, you need to feed the hits from the first list, as arguments to the second list.

In Views, you can add a `Contextual filter`, or `Argument`, depending on your version. These arguments can be set to "exclude" their matches, and it's also possible to allow "multiple arguments per filter".

The high priority View can be left as it is, but the low priority View should be configured so that it takes several entity-id's as arguments, and excludes those from the result. The real difficulty for most is going to be in passing arguments between these two Views.

In code:

```
$first = views_get_view('most_important_view');
$second = views_get_view('less_important_view');

// Get results, but don't render them.
$first->preview('machine_name_of_display');

// Append together a list of node id's to a string.
$nodes_to_exclude = '';
foreach($view->result as $node) {
  $nodes_to_exclude .= $node->nid . '+';
}
// Remove the trailing +.
$nodes_to_exclude = rtrim($nodes_to_exclude, '+');

$second->execute_display('machine_name_of_display', array($nodes_to_exclude)););
return $second->render();

```

If you are not comfortable using the above code, there is a module called Viewfield that allows you to call a second View from a primary View. But unfortunately I'm not aware of a way to configure this to pass several arguments on, but just a single one, so I'm not sure if that's helpful.
> 5 votes

# Answer
I was recently viewing videos about the Rules module at dev.nodeone.se, and it discusses such a situation. Check it out.
> 0 votes

# Answer
A module exists to accomplish this. It started within Drupal 6. It is Views exclude previous. Details from project page:

> The Views exclude previous module provides a views filter that excludes nodes that have already been loaded/displayed on the current page.
>
> This is very useful when you have pages with several embedded views, and you want to make sure that a given node only appears once in the page.
>
> The advantage of using Views exclude previous rather than manually excluding nodes is that:
>
> * Each view does not need to know which context it will be displayed in
> * Each view can be displayed in a different context (different page, different order) without needing to change the filter
> * Only the nodes that are actually displayed are taken into consideration - not those that would fall beyond the first page of the pager

Believe it relies on keeping track of node loads, so it won't work with field-based views and perhaps not with other entities. I'm sure the module could use some love.
> 0 votes

# Answer
I think the best way to achieve this is use selection rules (I'm not completely certain if you can filter by those properties but I think you can). I'm not really sure how you are going about defining "new" and "popular" but if is something that can show in the selection rules you can use that to filter.
> -1 votes

---
Tags: 7, views
---


# Question
Title: How to show order total components in a block?
I would like to create a block that shows the current user's order totals including all components, as follows:

> ```
>  - Subtotal
>  - Discount or coupon
>  - Sales tax
>  - Total
>
> ```

I would be happy with a block that simply renders the footer of the shopping cart view. I've played around with *commerce-line-item-summary.tpl.php*, but it only renders the number of items in the cart and the total amount. It doesn't have to be a form, just a summary of the shopping cart totals.

I would like to show this block during the checkout process in a sidebar region.

Any ideas how to create this?

# Answer
> 1 votes
Quoting @Clive from the comments above:

> Commerce has a "Commerce Order: Order total" component that can be used in Views- it does exactly what you're looking for.

Thank you!

---
Tags: 7, commerce
---


# Question
Title: Display add to cart form / +product from node template
I have a custom node template based on a custom content type and I want to display products with their "Add to Cart" buttons from this custom node template.

In the content type (actually a field collection), I added the Product reference. In the template (node--{content type}.tpl.php) I do this type of thing:

```
$wrapper = entity_metadata_wrapper('node', $node);
// Since it's a field collection, I loop these:
foreach ($wrapper->field_content_group as $group) {

  //Now each "$group" has the fields I want to display

  //I permit N products (not just 1), so I can get product information,
  //like price for example, like this:

  if($group->field_featured_product) {
    $product_references = $group->field_featured_product->value();
    foreach($product_references as $product_reference) {
      $product = commerce_product_load(intval($product_reference->product_id));
      $price = entity_metadata_wrapper('commerce_product',
                                       $product)->commerce_price->value();
      print $price_display = commerce_currency_format($price['amount'],
                                                    $price['currency_code'], $product);
    }
  }

}

```

I don't need to alter the display, I'm happy with that. I'd like to just call something that prints the product, price, etc., along with the "Add to Cart" button. I'm thinking I call commerce\_product\_load and then some method(s) that gives me the completed form. Is there such a thing that I can call?

NOTE: Yes, I know about separation of concerns and that code is best placed outside of the template file.

# Answer
> 0 votes
Since views seem to be the easiest way to display product offerings, the way I solved this was to create views for the products. The views are configured as blocks. Then I use:

```
$block = module_invoke('views', 'block_view', $block_name);
print render($block['content']);

```

to display the block.

I used content type fields to specify the block names I want to display within certain areas so it isn't hard-coded. It isn't terribly elegant, but sometimes programming is that way since there isn't an infinite amount of time to solve problems!

# Answer
> 0 votes
There is an alternate way of doing this, as shown by duckzland on drupal.org:

**Note**: You may need to alter the product retrieval code slightly to match the way your node is set up. Using `var_dump($content)` should help you determine the structure.

Load your product through the node template, without calling `commerce_product_load()`:

```
<?php
$view['product'] = NULL;
// retrieve raw product from field containing your product's info
if(isset($content['product:field_featured_product']) {
    $view['product'] = $content['product:field_featured_product'];
}
// do stuff to output the product here
// add to the cart here
// build the line items for shopping cart
$order_id = 0; // optional
$line_item = commerce_line_item_new($view['product']->type, $order_id);
$line_item->data['context']['product_ids'] = array($view['product']->product_id);
$line_item->quantity = 1;
// need to create config for quantity
$qty = 1;
$form_id = commerce_cart_add_to_cart_form_id(array($view['product']->product_id), $qty);
$addtocart_form = drupal_get_form($form_id, $line_item);
// we alter the submit form to use our special theme function
// need to move this to configuration
$addtocart_form['submit']['#theme'][] = 'vtcommerce_button_small';
$variables['cart'] = render($addtocart_form);

```

---
Tags: commerce
---


# Question
Title: Is it possible to provide content editor ability to create sortable table?
I know how to create a sortable table using

```
theme('table', $headers, $rows)

```

but is it possible to create a functionality so that a content creator can create a sortable table inside a content. For example creating a sortable table inside a node.

# Answer
You can use TableField module to create table that is a real html table. Sorting is currently unsupported, sadly, although it would be wonderful.

If all you need is sorting on display, you can create a patch or your own module, and implement one of the jQuery plugins for sorting. Personally I found tablesorter to work pretty OK.
> 2 votes

# Answer
see drupal\_add\_dragtable()

> Assists in adding the tableDrag JavaScript behavior to a themed table.
>
> Draggable tables should be used wherever an outline or list of sortable items needs to be arranged by an end-user. Draggable tables are very flexible and can manipulate the value of form elements placed within individual columns.
> 0 votes

---
Tags: nodes, theming
---


title: Drush cc all 'Killed'

text:
# Question
Title: Drush cc all 'Killed'
With a D6 instllation I am seeing 'Killed' returned whenever I try to clear the Drupal cache.

Verbose output gives me this:

Initialized Drupal 6.30 root directory at /var/www \[notice\] Intialized Drupal site default at sites/default \[notice\] Undefined variable: may\_cache feed\_field.module 12 \[notice\] Killed

# Answer
This is most likely a system issue. I have had similar issues when using middleware on our db servers. For example, if you are using tungsten as a db replicator, it could be configured to disable certain queries or anything that takes longer than a predefined value. This is a mysql or middle ware configuration that is killing a process that takes longer than expected. Similarly, from another SA question

> you might be triggering the Linux out-of-memory (OOM) killer. Check dmesg for messages about it. It says which process was killed when this happens.

You can use `dmesg | grep php` for further information
> 0 votes

# Answer
The string "Killed" doesn't exist in the Drupal 6.30 codebase.

You might have a custom/contrib module which is responsible, or perhaps a Drush extension.

If that's the case, to find it:

```
grep -nr "Killed" /path/to/drupal/root
grep -nr "Killed" /path/to/drush/extension/folder

```

(The extension path will probably be ~/.drush)
> 1 votes

# Answer
I increased the PHP memory\_limit to form 196M to 256M in the php.ini and the command now executes as expected so it was a memory issue as suspected by @awm.

I'm not sure what had changed to cause Drush to consume more memory however and whether it's safe to allow php scripts to consume so much memory.

For for the help all.
> 1 votes

---
Tags: drush
---


# Question
Title: Request to reset the password ask current password
My problem with Drupal is that when I choose "Request new password" and submit, it sends me a email with a link

> example.com/?q=user/reset/69/1376903015/wiUMZxM27RkYYAAr6zHZfqz6BH4sVMHDAfGoaeZT-Cc

I can login to account by clicking over that link. When I do the same it logged in me and redirects me to user edit page

> example.com/?q=user/69/edit&pass-reset-token=-yS11phdH8HuId-5wpaKrdI6KyWOtfV098jZ5mXb\_C0

Now I want to reset my password but when I click on password tab `example.com/?q=user/69/password`, it ask me my account's current password. But I (may be a user) don't know current password . So How can I change password?

One point I noticed that when I put pass-reset-token on the password change URL like this

> example.com/?q=user/69/password&pass-reset-token=-yS11phdH8HuId-5wpaKrdI6KyWOtfV098jZ5mXb\_C0

I can reset my password without putting current password.

It means that token does not apply on the password tab link. Do I need some module or change in core user module to rectify this problem?

## WHAT I DID FOR TIME BEING / TEMPORARY SOLUTION

I edited file : modules/user/user.pages.inc //on line Number 142 updated

```
drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));

```

to this

```
drupal_goto('user/' . $user->uid . '/password', array('query' => array('pass-reset-token' => $token)));

```

Changed "edit" to "password"

Now my goal is complete. I know it not a good solution.

Any suggestion or answer would be appreciated.

# Answer
I edited file : modules/user/user.pages.inc //on line Number 142 updated

```
drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));

```

to this

```
drupal_goto('user/' . $user->uid . '/password', array('query' => array('pass-reset-token' => $token)));

```

Changed "edit" to "password"

Now my goal is complete.
> 0 votes

# Answer
No Current Password module allows you to make this field optional.

Also, there's an issue in core about this.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Display distance Coordinate vs Zip Code?
I am trying display Coordinate vs Zip distance. User inputs zip they get a list of things close. Trying to work with Openlayers and expand on this post. Need a simple Google Maps solution; lost in the labyrinth of modules

# Answer
> 0 votes
This tutorial helped me when i set my first proximity search.

It goes through eveything you need, and once done, is easily configurable.

---
Tags: views
---


# Question
Title: How to disable CKeditor for a particular node?
I want to style the content within a particular node but the CKeditor seems to interfere with that by introducing unnecessary tags.

In Drupal 6 you could disable it by adding the generated id on the node form to the profile settings of ckeditor.

I could find no similar settings in the Drupal 7 version.

Am I missing something here? Is there no similar configuration for Drupal 7?

or should I go with a hook\_form\_alter?

Any help is appreciated.

# Answer
> 1 votes
You can configure text formats to have different editors with WYSIWYG API, all you need to do is create a new format (like Full HTML) and set it for no editor, then on any node you don't wish to have an editor, simply set the text format to your new custom one.

# Answer
> 0 votes
When editing the node, simply choose *Full HTML* as your text format, configure the html tags as you wish, and save the node.

If you save the node with a different text format selected, CKEditor is not active.

# Answer
> 0 votes
I disabled ckeditor in the new private message form using hook form alter.

```
function mymodule_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_new') {
    $form['body']['#type'] = 'textarea';
  }
}

```

this works for me. this didn't disable other fields. just the ones i wanted.

---
Tags: 7, wysiwyg
---


# Question
Title: Privatemsg module shows admin and myself in autocomplete
I am using Drupal 7. In the Privatemsg module my autocomplete shows myself and admin. How can I disable displaying the user who's logged in in the autocomplete and disable displaying admin?

# Answer
> 1 votes
**Put this code in your template.php file**

```
function yourtheme-name_query_privatemsg_autocomplete_alter($query) {
  global $user;
  $query-> condition('u.uid' , $user->uid, '<>');
}

```

---
Tags: ajax, privatemsg
---


title: Set drush alias for current path

text:
# Question
Title: Set drush alias for current path
Is it possible to associate a path with a specific drush alias?

Use case:

I'm on my local dev machine and I'm in /var/www/site1 when I run drush I want it to run as drush @site1 without me having to append @site1 every time.

My alias files are all stored in the my local home directory.

# Answer
> 2 votes
If you store settings.php in the default folder, then Drush will already behave as you desire. If settings.php is in some other folder (e.g. 'site1'), see the site-set command (`drush help site-set`)

---
Tags: drush
---


# Question
Title: Using rules to grant new role upon visiting page
Using the modules "rules" and "rules linkevent" I am trying to get drupal to automatically assign a new role to the user upon visiting a certain page.

I've written it like this/entered the following values and selected these options:

-

Events Event
levelup2 was accessed

-

Conditions Elements

User has role(s) Parameter: User: \[site:current-user\], Roles: authenticated user

-

Actions Elements

Add user role Parameter: User: \[site:current-user\], Roles: Level 2

---

What am I doing wrong or how could I alternatively make the user accessing the page, reading the page or another trigger I can make be granted a new role?

I have tried searching the net but have found no answers. Can anyone help?

# Answer
> 0 votes
The Rules Path and Rules URL Argument modules trigger events based on the current URL being viewed.

You could also use the Rules Link module to generate a custom link that will trigger your rules. The catch here is that this specific link must be clicked to access the page and the user I believe must be signed in.

If you need fine tuned control over when the Rules event is triggered you could even implement your own Rules Event.

# Answer
> 0 votes
You could use page manager with the rules bonus pack to achieve what you want. Watch this screen cast: http://vimeo.com/25153525

---
Tags: rules
---


# Question
Title: One of two field is required in drupal 7 view?
I have one view in which i want to upload picture(image) or embed video(text). I want to add condition either picture or video field required. and also user can not fill both value user can fill only one value.

I also tried to use https://drupal.org/project/conditional\_fields but it can not work for me.

I reffered https://drupal.org/node/355264 . I hope this will help me but I am new in Drupal so how can I used this.

Any help will be appreciate.

Thanks in advance.

# Answer
> 1 votes
An approach could be adding a previous radio button field where the user must select which field is going to fill, and the show this field with conditional field. (Both fields should be required)

---
Tags: views, entities
---


# Question
Title: Alter dynamically line item price on cart (drupal commerce)
I want to alter a product price (for example saved at 0.70€ in store). I pulled the hair several hours to find how to change the unit price (and the impact on the total price by changing the quantity) when putting the cart and / or from the time we are on the cart .

In fact, I need a base price, and according to certain client I modified by an external data (webservice). This modified price should not be saved but just used to that moment until the checkout process is complete.

In everything I tried, including the hook\_commerce\_cart\_line\_item\_refresh() the price is never changed.

An idea to save me?

# Answer
> 2 votes
Have you read any of the product pricing rules documentation or watched the tutorials on DrupalCommerce.org? It's all in there: http://www.drupalcommerce.org/user-guide/product-pricing-rules-screencasts

In other words, you shouldn't be hooking into anything, you should be using Drupal Commerce's core product pricing rules system. This is the only supported way to make consistent line item unit price alterations that are reflected in the final order total.

---
Tags: commerce
---


# Question
Title: What's the differences between these 2 queries to publish/unpublish nodes?
I found these 2 queries to publish or unpublish a node programmatically:

```
db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

```

I do not understand the difference, and not sure which one use.

Any suggestions?

# Answer
> 4 votes
Let me explain you with all details....

Your First Query is update statement on `node` table in drupal database which sets node to publish for a particular nid...

```
db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

```

Node table is a base table which stores node related information..

Your Second Query is on `node_revision` table which stores node revisions if you track node revisions which are nothing but updates...

```
db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

```

It's discouraged in Drupal to run queries directly on Drupal for certain actions.. For example in your case you are updating a node and setting status to published.. Drupal works using concept of hooks which are events and actions.. If any module is implementing any node related hooks they won't fire if you run queries directly.. So it's discouraged..

Right way of doing above action is using node\_save api function in Drupal 7...

```
$node = node_load($nid);
$node->status = 1;
node_save($node);

```

---
Tags: database
---


title: Drupal render form not rendering a form

text:
# Question
Title: Drupal render form not rendering a form
I have a cutom module which creates a page with a custom form. the problem is that i don't print whole form at once like :

```
$form = drupal_get_form('custom_example_form', $adverts);
print render($form);

```

Rather my code is like:

```
$form = drupal_get_form('custom_example_form', $adverts);
print render($form['name']);
print render($form['descriere']);
print render($form['submit']);
print render($form['form_id']);
print render($form['form_build_id']);

```

The problem us that is second example drupal is not generating

```
<form id="" accept-charset="" method="" action="">

```

How do i generate in second situation?

# Answer
You should not print individual children elements of the form array, but render it completely (with `render($form)`).

If you want to fine tune the markup inside the `<form>` tag, you need to alter the form (using `hook_form_FORM_ID_alter()`) or provide a custom theme used for the form (i.e. in `hook_theme()` returns an items with the form ID as key).
> 2 votes

# Answer
If you are selectively rendering the form, you could unset some fields and render the whole form.
> 1 votes

# Answer
I ended using this method to solve my issue, not an elegant solutions but it works:

in tpl:

```
$form = drupal_get_form('custom_example_form', $adverts);
print '<form id="'.$form['#id'].'" accept-charset="UTF-8" method="'.$form['#method'].'" action="'.$form['#action'].'">';
print render($form['name']);
print render($form['descriere']);
print render($form['submit']);
print render($form['form_id']);
print render($form['form_build_id']);
print '</form>';

```

it doesn't look good but is working.
> 1 votes

# Answer
Try This,

```
$form = drupal_get_form('custom_example_form');
print render($form);

```
> 0 votes

---
Tags: forms, theming
---


# Question
Title: MegaDrupal MD.Foto: Module dependency displaying incompatibility status
I've downloaded the MegaDrupal MD.Foto theme. The feature module for MD.Foto has a few dependencies. One of the dependancies is on Chaos Tools, which I loaded. After doing so, I noticed that the Panels module began displaying the incompatibility message:

Requires: Panels (disabled), Chaos tools (\>=1.4) (incompatible with version 7.x-1.2)

What do I need to do to correct this?

# Answer
> 0 votes
If you *think* Ctools 7.x-1.4 is the one you installed in your system and that Drupal wrongly detect it starts by clearing the cache. Then searh ctools.info file in your web root, if you find more than one, then you have duplicate installation of the Ctools module. Likely one of then is too old but is the one picked by Drupal. Remove it. If not, check the version in this file.

---
Tags: 7
---


# Question
Title: #attached property doest't work!(render array/form api)
the css file style.css never get loaded when using the form api #attached properties. here is my code:

```
mymodule_menu() {

  $items['test'] = array (
            'title' => t('test css'),
            'page callback' => 'drupal_get_form',
            'page arguements' => array('test_attach_css'),
            'access callback' => TRUE,
            );

return $items;

}

function test_attach_css($form,$form_state) {
   $markup = '<p class="test">style the font as red</p>';
   $form['content']['#markup']  = $markup;
   $form['content']['#attached']['css'][] = drupal_get_path("module",       "mymodule")."/style.css";

return $form;
  }

```

the content of css file:

.test {

```
 color:red;

```

}

# Answer
> 0 votes
after many hours of searching and debugging for an anwser, i finally realize it's a naming issue. you cannot name the css file as style.css. i changed the name to custom.css,then it works as expected!

---
Tags: 7
---


title: Rendering field cases unexpected error

text:
# Question
Title: Rendering field cases unexpected error
Hey guys I tried to render a field on to the page template and it works fine on all pages except login/registration/profile pages.

Here's the code:

```
    <h3>
     <?php print render(field_view_field('node', $node, 'field_introduction', array('label'=>'hidden'))); ?>
    </h3>

```

Here's the error:

# Answer
You need to load the node to render it if the page you are viewing is other than node page... In node page page.tpl.php contains $node object.. See page.tpl.php documentation for more details...

> $node: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

If other than node page you need to load the specific node from which you want to render the field in your login/registration/profile pages.. You can override page.tpl.php for specific pages.. For more details see Template suggestions..

To load the node specifically you can use node\_load API function...

```
$node = node_load($nid); // Where $nid is node id

```
> 0 votes

---
Tags: entities, theming
---


# Question
Title: how to display unique records between two table by using db_select query in drupal
The following two tables contained `reg_no` field. how to get unique `reg_no` records of the `student_master` table

**for example**

student\_master table

**reg\_no**

MA1001

MA1002

**semester\_appear** table

**reg\_no**

MA1001

but I want to get output only **MA1002**. how to get the output by using following code

**Table : \**Student Master\****

```
$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$query->orderBy('reg_no','ASC') ;
$results = $query->execute();

```

**Table : semester\_appear**

```
$sem_query = db_select('semester_appear');
$sem_query->fields('semester_appear', array('reg_no','batch_year','month','year','subject_code','sub_serial_no','semester_appear'));
$sem_query->distinct();
$sem_query->condition('year',$year,'=') AND $sem_query->condition('reg_no',$reg1,'=') AND $sem_query->condition('semester_appear',$semester,'=') AND $sem_query->condition('month',$month,'=') AND $sem_query->condition('marks_updated',$no,'=') AND $sem_query->condition('batch_year',$batch,'=') ;
$subject_results = $sem_query->execute();

```

# Answer
I have found that the easiest way to do complex MySQL queries (including JOIN, which is what you're after here) is to use db\_query(): https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_query/7

And the MySQL docs explain the JOIN syntax quite nicely: http://dev.mysql.com/doc/refman/5.0/en/join.html
> 0 votes

---
Tags: forms, database
---


# Question
Title: What is the benefit of Panels Everywhere
Several websites advocate the benefits of Panels Everywhere (I have put them at the end of this question).

However, I have tried the module out out and cannot see the benefits.

A regular Panel page gives you the option to Disable Blocks. It also lets you display things like Menu Links, Footers and User Log-ins. So I'm not sure what Panels Everywhere brings.

I could never see the benefits of Panels, but Drupal Answers enlightened me and now I wouldn't dream of making a Druapl site without it, so I'm hoping it can shed some light on the benefits of Panels Everywhere).

---

Sites Advocating Panels Everywhere

1. AWebFactory
2. Druapl Answers Thread
3. Lullabot

# Answer
My experience with PE (panels everywhere) was great. I been working for 1 year with PE on a big project and i can say:

* The first advantage of PE is the entire layout control. while panels only affect the "content" region, PE get full control of all page including header and footer (which is no possible only with panels).
* Second big advantage its the possibility to select variants as layouts letting you decide wich layout (variant) to show on every page taking that decision with the access arguments like a normal panel.

as you can see there are similarities with Omega theme, and in the fact both modules resolves the same issue.
> 9 votes

# Answer
Besides the layout creation and management tools, there is another advantage to Panels: performance. Although not that apparent on smaller sites, it can have a major impact on larger installations. If a site is created using the standard Drupal block system, all blocks must load, and then not displayed (if set as so), instead of only pulling appropriate content for the given visitor.
> 2 votes

# Answer
One of the main advantages of Panels Everywhere is that it lets you override pages that regular Panels does not allow (such as node/add, user, etc).
> 1 votes

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


# Question
Title: drupal_add_js and variables into anonymous functions, objects undefined?
Pulling my hair out. Read a lot of stuff about scopechain and closure to tackle this one myself. And as i understand at some level, i can't get this to work.

I wrote a module for likebuttons (like facebook twitter etc). It's working ok, but I want to make it more generic and multilingual. I did the following. In my facebook function I have this:

```
<?php
  $lang = 'en_EN'; //

  // Load javascript
  $settings['lang'] = $lang;
  drupal_add_js(array('mymodule' => $settings), 'setting');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/myscript.js');
?>

```

This is working ok. The javascript gets loaded and the $settings\['lang'\] is passed to browser too (as I can see in chrome console it gives me 'en\_EN' on Drupal.settings.mymodule.lang).

In myscript.js script I have the following (simplified to be a more generic question

```
(function() {

  var language = Drupal.settings.mymodule.lang;
  console.log(language); //undefined

}());

```

UPDATE: So it's anonymous.... All those terms. Ok, got the object inside now. Now i got to figure out how to get the 'en\_EN' from the object.

Updated script:

```
(function(language) {

var my_var = language.settings.mymodule.lang;
console.log(my_var); // undefined
console.log(language); //Object { settings={...}, behaviors={...}, locale={...}, meer...}
console.log(language.settings); //Object {}
console.dir(language.settings) // There are no underlying objects
}(Drupal));

```

Here language contains the complete object drupal has passed. (I can see that in console).

Why can't I go in the object language like normal and get my value by using language.settings.mymodule.lang?

Seems like Drupal.settings is empty inside the anonymous function, but has all elements there in the DOM tree. I don't know what causes this to be an empty object inside an anonymous function.

# Answer
> 1 votes
As of Drupal 6 javascript is put inside function that we assign as a property of *Drupal.behaviors*. Example,

```
Drupal.behaviors.myModuleBehavior = function (context) {
  //Do some fancy stuff
};

```

Drupal 7.x:

```
Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
    // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};

```

So your code should be

```
(function($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      var my_var = Drupal.settings.mymodule.lang;
      console.log(my_var);
      console.log(language);
    }
  };
})(jQuery);

```

---
Tags: javascript
---


# Question
Title: Clean URL in Exposed Filters in Drupal 7
How can i get a clean URL in my Exposed Filter and Contextual Filters. I want to create a archive were users can sort the nodes by its posted Date. I used contextual filter to achive this and its working fine when i pass the value in URL like.

"www.example.com/archive/10/09/2013".

But when i use a exposed filter and submit the value the URL became like this

"www.example.com/archive/archive?date\_filter%5Bvalue%5D%5Byear%5D=2013&date\_filter%5Bvalue%5D%5Bmonth%5D=9&date\_filter%5Bvalue%5D%5Bday%5D=10" and it returns a empty page.

How can i pass a clean value in Exposed Filter and make it work properly? Thanks in advance.

# Answer
> 1 votes
You will probably have to split this off into two different views displays, one for the clean URL with contextual filters and one using the exposed filters.

The only other way I can think of is making the contextual filters optional, but that may not be possible.

---
Tags: views, uri, backups
---


# Question
Title: If statement for page template in node template file
Is it at all possible to check for a page template NID before outputting some text in a custom node template file?

I have a custom node template file and I am using that data in a custom page template file. I have checked in the past the NID of a node using the following that that works:

```
          if (($node->nid) == '25732') {
            print views_embed_view('lead_view',"page");
          }

```

Now I want to check whether the page template file is 1234. I tried using $page, but I don't think that is right.

```
          if (($page->nid) == '1234') {
            **Stuff here**
          }

```

# Answer
you can do this like

```
if(arg(0) == 'node' && arg(1) == '1234'){
**Stuff here**
}

```
> 0 votes

---
Tags: 7, theming
---