# Question
Title: Search option just as that provided in drupal.org
can you please tell me which module to use to provide search options just as the search provided in https://drupal.org/download

Thanks

# Answer
> 2 votes
Facetapi module will help you. From facetapi module page:

> The Facet API module allows site builders to easily create and manage faceted search interfaces.

You may also look into search\_api module. From module page:

> This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc.

If you do not want to use the default Drupal search you can use apachesolr search module. This module can also be integrated with facetapi module.

# Answer
> 2 votes
It's Solr filters. If you don't setup it, you can just use Views Exposed Filters - simplest way.

Other solution - Search API \- that have count of integrations for expanding search page.

---
Tags: search
---


# Question
Title: Display an image through page.tpl.php only on front page
I want to display an image only on front page through page.tpl.php... However i am not sure about the syntax or where i am going wrong as the code that i type in leads me to en error (syntax error)...here's the code:

```
<?php  if (drupal_is_front_page())
    {
        <div id ="join">
           <a href="/node/38"><img src="/sites/all/themes/ypwb/joinb.png"></a>
        </div>
    }
?>

```

# Answer
You need `?>` after the opening parenthesis and `<?php` before the closing parenthesis. This is so-called embedding HTML among PHP coding.

Most likely, you can use parenthesis, but you can see the default theme Bartik uses the alternative syntax for control structures (:).

```
<?php if (drupal_is_front_page()): ?>
    <div id ="join">
       <a href="<?php echo drupal_get_path_alias('node/38'); ?>">
         <img src="<?php echo drupal_get_path('theme', 'ypwb').'/joinb.png'; ?>">
       </a>
    </div>
<?php endif; ?>

```

You could use page--front.tpl.php as subhojit777 suggested, whereas you are right to use drupal\_is\_front\_page().

As a side note, you should use drupal\_get\_path\_alias() for your node path and drupal\_get\_path() for your image path.
> 4 votes

# Answer
Rather than editing in `page.tpl.php` which applies on all pages, you should create a template file called `page--front.tpl.php` and add image there if you want to display the image only in front page.

**EDIT**

For more theme hook suggestions refer this page
> 5 votes

---
Tags: 7, theming, media
---


title: Printing a block in node.tpl.php

text:
# Question
Title: Printing a block in node.tpl.php
Would appreciate it if someone could let me know how to print a block in node.tpl.php. I basically have a block created through a view and I haven't set a region for that block as I would like to do is display this block in a specific position in all my node pages.

This is what I did in my theme's template file:

```
function mytheme_preprocess_node(&$vars) {
  $vars['my_block'] = mytheme_block_render('views', 'myblock-block_1');
}

function mytheme_block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}

```

And in my node.tpl.php file, I just do:

```
<?php print $my_block; ?>

```

However, this is giving me a memory limit exhausted error. I can get it to work perfectly if I render the block in mytheme\_preprocess\_page function and print it in page.tpl.php, but I need to print this in node.tpl.php. I tried the following as well:

```
function mytheme_block_render($module, $block_id) {
  $block = module_invoke('views', 'block_view', 'myblock-block_1');
  return render($block);
}

```

That is giving me the same memory exhausted error. Is it too later to render a block in the node preprocess function? Why can I render it in the page preprocess function but not in node? Is there some other preprocess function that we can render it in and then have access to it in node.tpl.php?

# Answer
> 7 votes
I think module\_invoke() is correct and you can simply call that in your tpl file. However,

use

```
print $block['subject'];

print $block['content'];

```

instead of

```
print render($block);

```

Also

**D6 and earlier:**

```
$block = module_invoke('module_name', 'block', 'view', 'block_delta');
print $block['content'];

```

**D7:**

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

```

*Refer*

for more some more help.

# Answer
> 1 votes
I used to encounter memory limit problem whenever I installed the Views module on a fresh installation. I usually added `ini_set('memory_limit', '512M')` in settings.php. It resolved my problem.

In your case, I'm not sure why are you facing this problem when you render your block to the template.

You could also give a try hook\_node\_view from the module level.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        $block = module_invoke('views', 'block_view', 'myblock-block_1');
        $node->content['my_block'] = array(
            '#markup' => render($block['content']),
        );
    }
}

```

---
Tags: views, blocks, theming
---


# Question
Title: How to give meaningful id names to blocks?
Instead of styling with ids/classes such as `block-block-3` which may be deleted and then recreated, how would I go about giving my blocks meaningful names?

# Answer
Use the block class module. Block Class allows users to add classes to any block through the block's configuration interface.
> 8 votes

# Answer
You could also do something with hook\_preprocess\_block:

e.g, in template.php

```
function MYTHEME_preprocess_block(&$variables){

  // Add class including block-my-subject
  $variables['classes_array'][] = drupal_html_class('block-' . $variables['block']->subject);

  // Add arbitrary class to specific block
  if ($variables['block']->module == 'user' && $variables['block']->delta == 'login') {
    $variables['classes_array'][] = 'my-special-class';
  }

  // Add unique id including block-my-subject
  $variables['block_html_id'] = drupal_html_id('block-' . $variables['block']->subject);

}

```

As a purely theme based solution for a CSS class issue.

Keep in mind, the reason the default class and id are not like that is because the class or id will change if the block subject is changed, breaking any CSS rules there, whereas module name and delta are consistently unique for that block. as per

```
$variables['block_html_id'] = drupal_html_id('block-' . $variables['block']->module . '-' . $variables['block']->delta);

```

Nevertheless, worth mentioning you can add a unique class or id with hook\_preprocess\_block at the theme layer. No module required.
> 3 votes

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


# Question
Title: How can we configure the Master slave concept in Drupal 7?
I have one large scale website and hosted on AWS. I want to enable Master-Slave concept on it. How can it be possible to configure the same?

# Answer
> 3 votes
Yes, Drupal supports master/slave style database replication.

Note: master/slave replication configuration is done at the database server level. Drupal simply utilizes the replicated databases by using the slave server when one database isn't available, or for specific 'slave' marked queries ( see db\_query "target" option ).

See the fully commented default.settings.php for Drupal configuration details.

> For each database, you may optionally specify multiple "target" databases. A target database allows Drupal to try to send certain queries to a different database if it can but fall back to the default connection if not. That is useful for master/slave replication, as Drupal may try to connect to a slave server when appropriate and if one is not available will simply fall back to the single master server.
>
> The general format for the `$databases` array is as follows:
>
> * `$databases['default']['default'] = $info_array;`
> * `$databases['default']['slave'][] = $info_array;`
> * `$databases['default']['slave'][] = $info_array;`
> * `$databases['extra']['default'] = $info_array;`

# Answer
> 3 votes
You may want to try out the AutoSlave module.

> This database driver (called "autoslave") will automatically use the database slaves where applicable and otherwise use a master database.
>
> *Applicable* means:
>
> * The query is not a write query (and not a select query with locking)
> * The tables in the query have not been written to during the request and within the assumed replication lag
> * A transaction has not been started
> * The tables in the query are not specified in the 'tables' option in the driver settings
> * A lock has not been started (core db-lock and memcache-lock supported)

I'm the author of the module; if you decide to try it out, feedback is appreciated.

---
Tags: database
---


# Question
Title: How do I filter down on multiple taxonomies?
I'm trying to create a simple classifieds area e.g. think of Craiglist.

I have 2 taxonomies; Region and (Ad) Category.

Everything is fairly easy when using just the Category in the following way:

**Marketplace (views page)**

* Cars (5)
* Clothes (10)
* Electronics (14)
* etc.

**Category (views taxonomy page)**

Cars Listing of 5 nodes belonging to this category

Now, I want to bring along the Region but I am stuck on how to make it work with the listings I have. The user should be able to choose the Region before coming into the Marketplace or when on the Marketplace page. The number of items in each category would reflect on the chosen Region and consequently the Category pages would list only nodes that are in that Region.

What I've tried is to use the Views exposed filters and it works fine on some parts. The real problem is how to make it all flow from the beginning so that the Region information carries across the steps?

# Answer
For this case, exposed filters are the wrong approach.

You can do this by making a contextual filter that operates on your region vocabulary.

Assuming your view is set to display taxonomy terms, I would do the basic configuration like this:

1. Add a contextual filter of type **Taxonomy term: Term ID**.
2. Set *When the filter value is not available* to **Display a summary**.

When you do this, you should get a page that list the regions if you have not selected one yet but lists data if you have selected a region.
> 1 votes

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


# Question
Title: Is there any replacement module for token actions and token starter modules in D7?
I am using TokenActions and TokenStarter modules in my one of the project which is in D6.

Now, I have planned to upgrade it into D7.

**I have found the D7 version of Tokens module but I didn't find Tokens Actions and Token Starter in that module.**

Is that modules are removed are is it still existing in some other names?

I had googled a lot. But I didn't find anything really useful...

Coudl you guys help me out of this issue ?

# Answer
**From Dave..Mainter of token module... (As Received)**

The Token Actions module has been replaced by the actions provided by core that support tokens. Use the follow button on http://drupal.org/node/1902294 to track progress for migrating those deprecated actions to system-provided ones automatically.

The Token starter is not an actual module that is intended to be used. It's just an example of how you make new tokens. It was deprecated by the token example module in http://drupal.org/project/examples. You should instead make a custom module with a good name for your custom tokens, rather than re-using the token starter module.
> 0 votes

---
Tags: 7, updating, tokens
---


# Question
Title: Display list of user name with user points sorted by points based on certain time period?
We added user points for provide points to user, when creating node, comments and likes.

We created view for display user points list (user name, Total points, and ranks). It working fine.

But we need to display the above based on the certain period.

Thanks in advance. Provide any idea...

```
example
--------
1) From Jan-2013 to March-2013
------------------------------------
Rank   - Points  -  Name
-------------------------------------
1      - 50      -  user2
2      - 48      -  user1
3      - 40      -  user3
-------------------------------------

2) From April-2013 to June-2013
------------------------------------
Rank   - Points  -  Name
-------------------------------------
1      - 55      -  user3
2      - 54      -  user2
3      - 40      -  user1
-------------------------------------

3) From July-2013 to September-2013
------------------------------------
Rank   - Points  -  Name
-------------------------------------
1      - 55      -  user2
2      - 54      -  user3
3      - 40      -  user1
-------------------------------------

```

# Answer
> 0 votes
* In the contextual filter of the view add `Userpoints Transactions:
User`
* In views fields add `Userpoints Transactions: Timestamp`. I see that you do not want to display date in views, so mark it as **Exclude from display**.
* In grouping setting of your view select `Userpoints Transactions: Timestamp`

---
Tags: views, 7, userpoints
---


# Question
Title: How to retrieve last MySQL INSERT ID from db_merge()
I am using db\_merge for inserting or updating new records in my table. I want to get the last inserted record id from this table, Thank you.

# Answer
> 7 votes
While there is RETURN\_INSERT\_ID which can be used with db\_query(), I could not find a way to use with db\_merge().

```
<?php
  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' => $val1, ':arg2' => $val2);
  $last_id = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
?

```

I think you will have to retrieve the last ID with another query, but you would need to check with MergeQuery::STATUS\_INSERT.

```
$status = db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute()

if( $status == MergeQuery::STATUS_INSERT ) {
      $last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();
}

```

# Answer
> 0 votes
> I want to get the last inserted record id from this table...

You could do a second query, to get the latest inserted id:

```
$max_id = db_query("SELECT MAX(id) FROM {table}")->fetchField();

```

That will return the latest inserted id, but not the id of the latest updated.

# Answer
> 0 votes
Hey in Drupal 6 we can use

```
db_last_insert_id('table_name', 'name');

```

This gives the last inserted id.

# Answer
> -1 votes
You can use this.

```

      $node = db_select('table_name', 'f')
      ->fields('f', array('field_you_want'))
      ->condition('field', 'condition', 'expression')
      ->orderBy('id', 'DESC')
      ->range(0,1);
      ->execute()
      ->fetchAll();

```

---
Tags: 7, database
---


# Question
Title: Cck date field save not working properly
I am saving a date field and when i print the value as `print_r($node->mydate[0]['value']);` it is printing only year `2012`. This problem is only for one field. If i adds a new date type field in that content type that works perfectly.I checked all actions and in my custom code but still not found anything wrong with that. If i update timestamp value with my sql query using db\_query that still have problem. I can't delete my field because of my previous content. Please help.

# Answer
Solved problem just by renaming the field. I couldn't found any reason what the problem was. I didn't found anything related to this in my custom code either.
> 0 votes

# Answer
Check that the granularity on the field isn't set to year only. You can edit this by going to `admin/structure/types/manage/[CONTENT TYPE]/fields` and selecting "edit" on the appropriate field.
> 1 votes

---
Tags: 6, datetime
---


# Question
Title: AJAX callback not added using form_alter
I want to perform a AJAX callback to check the value of a custom field during user registration. Because the form is already built, I need to use hook\_form\_alter.

1. But, no callback is added using hook\_form\_alter. Maybe it is overwritten later on? Therefore, I tried `$form['#after_build']`.
2. But that fails too for the AJAX property. Adding another form element works perfectly fine.

The code:

```
/**
 * Implements hook_form_alter().
 */
function member_id_check_v2_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
    case 'user_register_form':
    case 'user_profile_form':
      $form['#after_build'][] = '_member_id_check_v2_ajax';
      break;
    default:
      break;
  }
}

function _member_id_check_v2_ajax($form, &$form_state) {
  $form['member_id_check_v2_callback_wrapper'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
  );

  $form['custom_field']['#ajax'] = array(
    'callback' => '_member_id_check_v2_callback',
    'wrapper' =>  'member_id_check_v2_callback_wrapper',
  );

  return $form;
}

function _member_id_check_v2_callback() {
    watchdog(WATCHDOG_DEBUG,'Callback worked!');
}

```

What am I missing? Thanks in advance!

# Answer
> 1 votes
You need to do the AJAX callback on `#process` callback as `#after_build` callback is too late to inject AJAX.

Check out the this link and the example code:

```
/**
 * Implements hook_form_alter()
 */
function kf_link_form_alter(&$form, &$form_state, $form_id) {
  if ('example_node_form' == $form_id) {
    //$form['field_link'][$language]['#after_build'][] = '_kf_link_field_link_after_build';
    $form['field_link'][$language][0]['#process'] = array('link_field_process', '_kf_link_field_link_process');
  }
}

/**
 * Custom form api process function
 */
function _kf_link_field_link_process($element, &$form_state, $form) {
  $element['url']['#description'] = '<div id="example-link"></div>';
  $element['url']['#ajax'] = array(
    'callback' => 'kf_link_ajax_callback',
    'wrapper' => 'example-link',
  );
  return $element;
}

/**
 * Custom ajax callback function
 */
function kf_link_ajax_callback(&$form, $form_state) {
  $values = $form_state['values'];
  $field_link = $values['field_link'];
  $language = $values['language'];
  $url = $field_link[$language][0]['url'];
  $duplicate_nodes = _kf_link_get_url_nid($url);
  foreach ($duplicate_nodes as $duplicate_node) {
    if (isset($duplicate_node->nid) && ($duplicate_node->nid != $values['nid'])) {
      drupal_set_message(t('This URL already exists in <a href="!url">!title</a>', array('!title' => $duplicate_node->title, '!url' => "node/{$duplicate_node->nid}")), 'error');
    }
  }
  $commands = array();
  $commands[] = ajax_command_html(NULL, theme('status_messages'));
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}

```

---
Tags: ajax, forms
---


# Question
Title: Set to the language of admin pages to english despite the language of front pages?
> **Possible Duplicate:**
> Do not translate the admin area / How can I set the language of the admin area to English?

Just that. I have a multilingual site but I'm very used to see the admin pages in english. Let's say I'm creating a new node in spanish then I see all in spanish language. Is there any way to set the language of admin pages to english despite the language of front pages?

# Answer
Administration Language module lets the administrator see all administration pages in their preferred language.
> 3 votes

---
Tags: users, i18n-l10n
---


# Question
Title: Assigning css class to a particular block
I want to add a CSS class to a particular block. I am using the module Block Class for it as shown in block\_class module. I am able to enable the module and assign the class by going to structures/block/configure. I am facing problem in where to add the php snippet. I am using a Zen starter kit theme and have copied the block.tpl.php from Zen/templates to my theme/templates and added the lines as specified...

Here's what my code looks like:

Before:

```
<div id="<?php print $block_html_id; ?>"
class="<?php print $classes;   ?>"
<?php print $attributes; ?>>

```

After:

```
<div id="<?php print $block_html_id; ?>"
class="<?php print $classes; ?> **<?php print block_class($block);** ?>"
<?php print $attributes; ?>>

```

# Answer
As far as I know, you don't have to add any code to use the class you set on structure/block/configure. The class should be automatically added to $classes array.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: How to apply function to a chosen region only?
I am using this template.php function:

```
function mytheme_menu_tree($variables) {
    return '<ul class="page_nav" id="pages">' . $variables['tree'] . '</ul>';
}

```

Now it applies to the menu no matter in which region it is. What if I want it to apply only if the menu is inside i.e. Top Menu region? I guess its something that needs to be added before *return* line?

Also I noticed another problem. It applies to all menus, i.e. if I have two menus, my *return* line applies to both menus, and 2nd menu is not even shown because id="" can be shown only once.

So I need that function to apply to the menu which is in Top menu region only.

# Answer
> 1 votes
You can use `theme_menu_tree__MENU_NAME()` to target a specific menu.

---
Tags: routes, theming
---


# Question
Title: Check if theme is enabled programmatically
How can I check to see if a theme is enabled on a drupal installation? I'm looking for something like module\_exists() but for themes. I couldn't find anything on the documentation.

# Answer
> 6 votes
Use list\_themes

### Parameters

**$refresh**: Whether to reload the list of themes from the database. Defaults to FALSE.

### Return value

An associative array of the currently available themes. The keys are the themes' machine names and the values are objects having the following properties:

* **filename**: The filepath and name of the .info file.
* **name**: The machine name of the theme.
* **status**: 1 for enabled, 0 for disabled themes.
* **info**: The contents of the .info file.
* **stylesheets**: A two dimensional array, using the first key for the media attribute (e.g. 'all'), the second for the name of the file (e.g. style.css). The value is a complete filepath (e.g. themes/bartik/style.css). Not set if no stylesheets are defined in the .info file.
* **scripts**: An associative array of JavaScripts, using the filename as key and the complete filepath as value. Not set if no scripts are defined in the .info file.
* **prefix**: The base theme engine prefix.
* **engine**: The machine name of the theme engine.
* **base\_theme**: If this is a sub-theme, the machine name of the base theme defined in the .info file. Otherwise, the element is not set.
* **base\_themes**: If this is a sub-theme, an associative array of the base-theme ancestors of this theme, starting with this theme's base theme, then the base theme's own base theme, etc. Each entry has an array key equal to the theme's machine name, and a value equal to the human-readable theme name; if a theme with matching machine name does not exist in the system, the value will instead be NULL (and since the system would not know whether that theme itself has a base theme, that will end the array of base themes). This is not set if the theme is not a sub-theme.
* **sub\_themes**: An associative array of themes on the system that are either direct sub-themes (that is, they declare this theme to be their base theme), direct sub-themes of sub-themes, etc. The keys are the themes' machine names, and the values are the themes' human-readable names. This element is not set if there are no themes on the system that declare this theme as their base theme.

Use path\_to\_theme to get active theme..

> It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.

# Answer
> 4 votes
The data is actually held in exactly the same place, the `system` table. I couldn't find an existing function to check (though there probably is one somewhere), but this should do in a pinch:

```
function theme_exists($theme_name) {
  $themes = list_themes();
  return isset($themes[$theme_name]) && $themes[$theme_name]->status == 1;
}

```

---
Tags: 7, theming
---


title: A Real Estate Website Using Drupal

text:
# Question
Title: A Real Estate Website Using Drupal
My friend wants me to create a Real Estate Search Engine for him where Users can submit Real Estate Information so that others can view them ( by searching or any other method ).

I want to use Drupal because I have worked with it earlier. If there is a plugin/add-on for Drupal which can help me make a Real Estate Website, please do include a link in your answer to the plugin or module page(The Plugin or module should be free of cost).

Is there any other CMS which I can use ( Real Estate Plugin should be available )? or should I go with Drupal?

# Answer
In Drupal, you will not find a specific "Real Estate Module". (Well, there is one, but it's a dev version for Drupal 5 and there's only 1 site using it :-)) Drupal modules tend to be more abstract: you take a module for building list pages, add a module for image handling, use a third module for send-to-a-friend functionality, etc. etc. The great thing about Drupal is that 99.9% of the time, you don't have to worry if those modules are compatible with each other. They just build on core concepts such as nodes, fields, menu's and users.

That said, I think you should be able to build a real estate site by combining the modules you need. This way, you will end up with a much more flexible system than a monolithic real estate plugin can ever offer.

I can't be really specific about which modules you need, because I don't know your exact requirements. For the basic functionality you don't even need additional modules; Drupal 7 core allows you to set up a content type (let's call it 'property'), add fields to the *property* content type (like an image field, price field, address field) and adjust permissions so logged in users (or anonymous, if you want) can create *property* nodes. Drupal core also includes basic search functionality.

After that, add contributed modules if needed:

* Views to create all kinds of lists (plain, with filters, sortable tables, etc.)
* Pathauto to create nice search engine optimized URLs
* things like Location, Gmap and/or Locationmap (I haven't tried them yet in D7) for maps and geolocations

I recommend that you start building a basic site first and ask more specific questions when you run into them.
> 8 votes

# Answer
You should try dRealty IDX for D7:

> dRealty is a Real Estate Module to import Listings into drupal via the RETS protocol. It aims to become a full fledged IDX solution for Drupal.
>
> dReatly IDX offers the following functionality:
>
> * Provides an interface to define multiple RETS service connections.
> * Provides an interface to Setup a MLS feed, allowing a user to import real estate listings into the Drupal system.
> * The module leverages the power of Entities, they are field-able!
> * Users have the ability to update and flush their MLS feeds
> * Integration with CTools to provide Importing and Exporting of connections
> * drush integration.
> * works wonderfully with search api
> 1 votes

# Answer
There is rListing - Real Estate Listing

Module can be found here https://github.com/vzeazy/rlisting

Looks like its paid now .. http://rlisting.com/

Give it a try..
> 0 votes

---
Tags: 7
---


title: Assigning User's In Taxonomy Terms

text:
# Question
Title: Assigning User's In Taxonomy Terms
> **Possible Duplicate:**
> Views: How can I show a list of users who have a taxonomy term attached via a term reference field?

i want to assign users profile in taxonomy terms. So, i have created a vocabulary like `Gender` which has two terms like `Male` and `Female`. So, while registering an account in my website people need to choose his/her gender, and i wish if other people click on those terms from some one profile page, for example if they click on `Male` then on the taxonomy page all profiles with `Male` will get appear and same for other terms. But i see no result on those terms pages, to find a solution i have created a `Views` which successfully show users profile for each terms.
Now, my question is how to integrate the `Views` for the terms pages?
|OR|
On user profiles how to link `Terms` pages to those `Views` page?

# Answer
> 1 votes
By default, the taxonomy term view lists **content (nodes)** and not **users**. If you want to use a new view on the default term page path, **taxonomy/term/%**, you have to **disable** the default view, create a new one, and give it that path. But it will also be in use for your others taxonomy terms pages !

So my advice is to **disable and ignore** this view, give a path to your full working new view, and set your **term path pattern** for this vocabulary the adress of your new view's page.

More simply :

1. Make a new view of users, set a "page" display and set it like this : /mypath/%
2. Add a taxonomy term ID argument
3. Add your fields
4. Go to your pattern url alias setting page, and for your vocabulary "gender", set terms URL to /mypath/% .

Now, all gender terms on your site will be linked to that view.

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


# Question
Title: Going from an installation profile to vanilla Drupal
I currently am using the Acquia Drupal installation profile on a site, and I want to convert it to a vanilla Drupal install. Other than cross referencing the modules that come with the profile, and making sure you download those from drupal.org and putting them into sites/all/modules, are there anymore steps that would need to be taken besides your regular update instructions?

# Answer
> 1 votes
Once a Drupal site is installed, it doesn't really matter which installation profile you used. The only difference is that it's possible to use modules and themes that are located in the profiles folder. So in that sense you are running vanilla Drupal.

If you want to disable the possibility to use the modules from the profile you need to, once you have added the modules to sites/all, set the installation profile to "standard". The easiest way to that is to use drush:

```
$ drush vset install_profile standard

```

# Answer
> 0 votes
Copying only modules doesn't help, but will closer. Installation profiles also run DB changes, so you need reproduce settings from code.

# Answer
> 0 votes
Just move the module files from the installation profile to sites/all/modules *before* you run the installation. After the installation you could even delete the profile.

# Answer
> 0 votes
here are some modified steps from This article: http://davehall.com.au/blog/dave/2012/09/12/switching-installation-profiles-existing-drupal-sites that worked for me.

```
$ drush vset -y install_profile my_profile

```

An alternative way of doing this is by directly manipulating the database. You can run the following SQL on your Drupal database to switch installation profiles:

```
UPDATE variable SET value = 'my_profile' WHERE name = 'install_profile';
-- Clear the cache using MySQL only syntax, when DB caching is used.
TRUNCATE cache;

```

Also you should:

```
echo "UPDATE system s SET schema_version = 0 WHERE s.name = 'my_profile'" | drush sqlc && drush cc all

```

Before you switch installation profiles, you should check that you have all the required modules enabled in your site. drush en $(grep depedencies /path/to/my-site/profiles/my\_profile/my\_profile.info | sed -n 's/depedencies\[\]=(.\*)/\1/p')

---
Tags: updating, distributions
---


title: "Illegal Choice has been detected"

text:
# Question
Title: "Illegal Choice has been detected"
I am dynamically populating `<select>` throught javascript in Drupal 7. The system gives me an error on submit:

"Illegal Choice has been detected"

How to mark, that this `<select>` must skip this error?

# Answer
To solve the problem set '#validated' =\> 'TRUE' in your form element definition.

```
Example:
 form['my_dynamic_select'] = array(
 …
 '#type' => 'select',
 '#validated' => TRUE
 …
 )

```

Reason:

If we are using a dynamically populated SELECT (dropdown) via AJAX this error will pop up. When a value is not present in options array, Drupal will consider it as illegal. So the user couldn't inject an illegal value into the database.

But in our case it's totally ok, so we need to use the attribute `'validated' => TRUE` to skip the validation.

Source: An illegal choice has been detected. Please contact the site administrator.
> 30 votes

# Answer
You need to do it on the server side, using a `hook_form_alter()` function and the `#limit_validation_errors` property of the Form API. You'll need to tweak it to suit your own needs but the following should help:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    $form['submit']['#limit_validation_errors'] = array();
  }
}

```

Be wary that the above will ignore *all* validation errors on the form. You'll need to put the names of the form elements that you *do* want to be validated in the `#limit_validation_errors` array.
> 3 votes

---
Tags: forms
---


title: Grabbing $_POST data

text:
# Question
Title: Grabbing $_POST data
# Background

A quick summary of where I stand right now:

We have a low traffic site here that was redone in Drupal about 8 months ago, before I was in the picture. An external design firm sold the owners on the technology as a way to enable non-programmers to update site content easily. Unfortunately, they did it wrong - they built our theme in-place over the Bartik theme instead of subclassing it, things like login boxes are written directly in the Basic Page Body textareas that our non-programmers are supposed to be updating, on and on and on beyond what's relevant to this post. Had I been here when it was forked over, I'm not even sure I would have taken delivery.

I've been meaning to pick up Drupal one of these days to go in and try to refactor this hot mess, but the non-Drupal work that actually keeps us all employed around here has prevented that.

Fast forward to now. I've got a feature request for the Drupal site that they want ASAP. It's a very simple application. Given the rush, I decided to develop the application as a straight PHP app to monkey patch onto the Drupal site. Based on some forms I had to maintain within the Drupal frontend (not using webforms, mind you) that I am able to $\_POST back to some non-Drupal PHP with, I thought I could get away with this.

Now as I am trying to integrate my super vanilla PHP code into our Drupal environment I am running into all sorts of problems. At first my $\_SESSION array wasn't persisting from page to page but I was able to figure that part out on my own by googling.

# TL;DR: The question

Where I am stumped is with my $\_POST array. I POST form data (an honest to God, completely naive HTML form) from one non-Drupal .php file to another non-Drupal .php file and it never arrives. The right way to do this - and the way it will get redone someday - is clearly to use the provided Drupal APIs for building forms.

Unfortunately, I am in such a position that there is absolutely, positively no time to rewrite this the right way today. With that in mind, is there a way to pass this POST data directly to the php file I am using for form processing?

## EDIT:

It looks like maybe I am getting redirected internally and the data is not coming along for the ride. Could this be it? If so, it looks like Forms specified using the API Drupal provides can do something like :

```
$form['# redirect'] = false;

```

to prevent their being redirected. Is there some perhaps hidden input field I could pass in with my non-Drupal forms to accomplish the same thing?

# Answer
> 0 votes
This wasn't a Drupal problem at all.

My problem was that I was getting an empty $\_POST array when I tried to process a naive HTML form with naive PHP. I was blaming this on Drupal because I'm unfamiliar with it but know enough about it to know that it changes the way $\_SESSION variables are to be handled (as arrays) and that we are on a pretty non-standard setup (as mentioned in the question).

The actual cause of the problem was something else entirely. It was a series of warnings in my Apache error logs that gave it away.

Part of what I was doing to sanitize the input from users was to use `mysql_real_escape_string()` on input. I didn't realize that this actually required an active connection to a mysql db. What was happening was that the Apache user under whom the php was executed did not have valid credentials to the db so the function was returning FALSE when it was unable to connect.

Remedying this situation caused `$_POST` to work as expected. It also explains why I couldn't find any documentation on how Drupal breaks $\_POST: it doesn't break it.

This answer isn't strictly related to Drupal but I've decided to include it after all so that any poor schmuck who finds himself going down the same dead end I was following can save himself a few hours of googling.

Further, `mysql_real_escape_string` is deprecated as of PHP 5.5.0 so you (I) should probably be doing this better anyway. And use Drupal's provided form API instead of rolling your own.

# Answer
> 0 votes
To tackle your exact question, let me first tell you that what happens in the form is the correct thing.

When you submit the form, it takes data, validates it and calls appropriate submit handlers to take care if the rest. The form, once its routing is completed, does a 302 redirect to the same location so a browser F5 hit does not resubmit data. It's a general practice to avoid double submissions.

You will need to make a module that alters the form using hook\_form\_alter and alter the form.

You can change form's action URL to the other PHP file or add an extra submit handler that posts data to the other raw php file using drupal\_http\_request.

You will find sanitized and structures data in $form\_state\['values'\] (second param of a submit handler is usually called $form\_state). $\_POST is also available at this stage.

---
Tags: forms
---


# Question
Title: Add Google Analytics JS file to every page
We use Google Analytics on each of our sites for our own reporting. We have implemented GA using the Google Analytics module, and everything works as expected.

However, I'm also part of a large organization that wants to start collecting analytics (using GA) on all of its sites. I've been given a .js file that I just need to add to the head of every page.

Should this be added in each site's theme or added to the GA module somehow?

Thanks for taking the time to look...

# Answer
Thank you @MDP and @Aboodred1 for your answers, both of which would solve the problem. However, I think I've discovered a way that is more appropriate for my situation. I'm adding it here for posterity.

We're going to create a small module that can be deployed to each of our sites. Has the benefit of being version controlled, can be turned on and off, and we don't have to maintain multiple copies of the js file. Plus, I don't have to dissect the JS file and possibly introduce errors accidentally. Thanks again.
> 0 votes

# Answer
When I have been in this situation, I use the GA module, look at the JS file that the organization give me, and then update the **Code snippet (before)** and or **Code snippet (after)** under the **Advanced Settings =\> Custom Javascript code** tab on admin/config/system/googleanalytics as needed.
> 3 votes

# Answer
If you already have the physical .js file I recommend you to add the .js file into your Drupal custom theme folder.

* add js file under `drupal/sites/all/themes/custom_theme/js`
* edit theme info file custom\_theme.info and add this line to it

scripts\[\] = js/your\_javascript\_file.js
> 0 votes

---
Tags: 7, javascript, google-analytics
---


# Question
Title: How can I write SelectQuery for SELECT LAST_INSERT_ID()?
Is it possible to run the following query with SelectQuery ?

```
SELECT LAST_INSERT_ID();

```

I would do this with db\_query(), but I'm finding a way to use the query builder.

```
$last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();

```

# Answer
Although the original query has no table name, `db_select()` would expect the table name.
The following works perfectly assuming the insert operation took place in another hook and the last insert id is not available into my hook:

```
$query = db_select('mytable');
$query->addExpression('LAST_INSERT_ID()', 'last_id');

$result = $query->execute()->fetch();
print $query;
echo '<br>';
echo 'Insert ID: '.$result->last_id;

```

Query output:

```
SELECT LAST_INSERT_ID() AS last_id FROM {mytable} mytable

```
> 0 votes

# Answer
If you need the last insert ID, after you executed an `INSERT` with the InsertQuery class, InsertQuery::execute() returns that value.

> The last insert ID of the query, if one exists. If the query was given multiple sets of values to insert, the return value is undefined. If no fields are specified, this method will do nothing and return NULL. That makes it safe to use in multi-insert loops.

Differently, UpdateQuery::execute() returns the number of affected rows.
> 0 votes

---
Tags: database
---


# Question
Title: Check new form-input against old form-input
I have added some extra options in the My Profile page which users can edit. But now I have to track down the change of this value...

It's a checkbox and whenever the user (un)checks this box, something must happen. So I thought this would be in the `$form_state`, but no luck there.

Next thing I did was to preform an EntityQuery on the user object and try to cross-reference it with the input, but again, no luck.

So how can I (programmatically) detect if a form-element goes from unchecked to checked or the other way around?

**EDIT:** What I try to do is an implementation with Campaign Monitor (a newsletter plugin). If a user has changed it's checkbox, his subscription must be updated (of leave it as it is when there is no change)

# Answer
> 0 votes
When you change something in form, that change can be found in `$form_state`. You need to add an AJAX callback and do your changes in that callback.

Sample code:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'MY_FORM_ID':
      $form['field_select']['#ajax'] = array(
        'event' => 'change',
        'callback' => 'your_ajax_callback',
        'progress' => array('type' => 'none'),
      );
    break;
  }
}

/**
 * AJAX Callback.
 */
function your_ajax_callback(&$form, &$form_state) {
  // dpm($form_state);
  // Check $form_state here and update subscription.
}

```

Hope this helps!

# Answer
> 0 votes
I have had a similar issue and I haven't found any easy answer. My solution was to create a "consistency check" function triggered after editing content, which would compare the values provided in the form with how things are actually set-up. If the values were inconsistent with the set-up I would know that they were changed.

In other words, whenever you edit the profile set things up whether they were changed or not. In case of editing a profile it will not be too heavy for the web-page.

---
Tags: 7, forms
---


# Question
Title: Facets and Apache Solr in Drupal 7 - Clicking Facets results in no results being show
I'm having a bit of an issue with Facets and Apache Solr, I'm not sure whether the fault lies with Solr or the Facets API.

I am using Solr as my search engine and I get results being shown when searches are performed, also shown are the amount of matches in specified fields/facets.

E.g. I search for 'content' - there are numerous values for 'content' within different categories such as 'category1', 'category2'

The search result shows as:

```
category1(5)
category2(7)

```

Implying there are 5 results in the facet category1, and 7 results in the facet category2, these are also links, however upon clicking these links the search shows as "no results found". Odd behaviour, has anyone experienced anything like this before? if so any pointers on where to look in order to resolve the issue?

I'm hoping this question is quite clear, if not just ask and I'll try provide some more details.

Thanks, Dan.

# Answer
> 2 votes
This is very odd behaviour, can you ensure you are:

* running the latest version of apachesolr (3.6.1)
* running the latest version of the apachesolr module (7.x-1.1) OR search\_api module (7.x-1.3)
* are running the latest schema.xml and solrconfig.xml (hopefully the 3.x version)

Also, try dropping and re-creating the entire index, this normally addresses more problems.

# Answer
> 1 votes
There are a large number of similar issues in the relevant issue queues for both Apache Solr and Search API Solr, because this could be a result of any number of errors. Here are some basic tips:

* Make sure you're using at least version 3.6.0 of Apache Solr (there are some outstanding bugs with Solr 1.4.x)
* Make sure you're using the correct schema.xml, solrconfig.xml, and other configuration files with Solr (see the installation instructions, and remember to delete your sites' index and reindex your content if you've modified those files)
* Check the Tomcat logs for your query; there should be a line for each query which includes the text "hits=123" where 123 is the number of results (if Solr is in fact returning results, your problem is specific to Drupal)
* If you're presenting results using views and you have an exposed fulltext search filter, make sure it's set as optional and not as input required

# Answer
> -1 votes
I would start by looking at how the url for the solr query is being built and testing it directly against the solr engine to see if it returns any results. I guess once you see the query built for the link you will understand why it returns 0 results. Happy hunting :)

---
Tags: search
---


# Question
Title: Modifying Drupal core (search module, image module)
I have a couple of modifications I did to the Drupal core:

* search module: I added a class to the `<ul>` that contains the "no-results" text.
* image module: I changed the 'title' attribute to have a #maxlength of 500 for a specific content type, so that only nodes of that type can have a longer 'title'

The question is: how would I do that without modifying the Drupal core? Is there a way of overriding those default outputs in a custom module? I'm looking for a way of doing that without touching the core, or to confirm that a modification in the core was the only feasible way.

# Answer
> 3 votes
I'm not sure how the second one is Image module-specific, but you would override that maxlength like so:

```
function hook_form_[content-type]_node_form_alter(&$form, &$form_state, $form_id) {
    $form['title']['#maxlength'] = 500;
}

```

... where 'hook' is replaced with the name of your custom module, and \[content-type\] is the machine name of your content type.

The API function is hook\_form\_FORM\_ID\_alter()

For the search form theming, you probably want something like template\_preprocess\_search\_results() in your template.php of your custom theme, and/or adding a custom search result template to the theme's templates folder.

Oh, and in case it needs saying again,

# DON'T HACK CORE

# Answer
> 2 votes
Definitely don't hack core. With the search module there are several .tpls in the module that you can copy to your theme folder and customize.

Regarding your image module changes, that would be done via a form\_alter in a custom module. It is worth the extra effort to learn it the "right way" because that is how you can maintain an upgrade path which is very important.

---
Tags: media, search, forms
---


# Question
Title: Detect profile2 save occasion in module and get user
Is it possible with custom module to detect occasion when user saves/updates his profile2 profile ? ( i know it is possible with rules but want to do it programatically in custom module).

And from that point, is it possible to load user data (the fields of profile2 profile) that just did the changes ?

Thanks for clues!

# Answer
> 2 votes
Yes it is possible, you can use the generic hook\_entity\_presave (or update/insert). There is also a specific hook for profile2 as well, hook\_profile2\_presave (or update/insert), but it requires the Rules module to be enabled.

# Answer
> 1 votes
I did this a couple weeks ago, with updating the users mailchimp info on saving the profile. Here is what I think you are trying to do.

```
YOURMODULE_profile2_update($profile) {
  // $profile contains the updated profile2 information so you can now
  // do whatever you would like to do with $profile info.
  // In my case I had to load the account again because I needed the
  // user object so I used:

  $account = user_load($profile->uid, TRUE);

}

```

For more information check out hook\_profile2\_update

---
Tags: users
---


title: Hook for Field Duplication

text:
# Question
Title: Hook for Field Duplication
I have a custom module that is formatting the display of an image field, which can accept multiple values. I would like to know what hook I should use to duplicate the first value of the field (e.g. "\[image1\]"), and add it back to the beginning of the array (with `array_unshift()` I guess) before the rest of my functions format the display/theme of the field.

So what was

* \[image1\]
* \[image2\]
* \[image3\]

becomes

* \[image1\]
* \[image1\]
* \[image2\]
* \[image3\]

I am then going to theme them separately, but I think I already have that part figured out.

I am currently using `hook_field_formatter_view()`, and have tried to just add it to the beginning of the `$items` array at the top of the function, but that didn't seem to work. If I immediately `dprint_r()` the `$items` array after this it shows, but only 3 items get output; I am assuming that the number of field gets determined elsewhere.

# Answer
You want hook\_field\_formatter\_prepare\_view() instead. Note this hook operate on a group of entities, not on a single one.

Here's a working snippet. Some array-fu is needed to not end up writing an ugly loop of ten lines, since deltas must be preserved linear.

```
<?php

function MODULE_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  foreach ($entities as $id => $entity) {
    $array = array(0 => $items[$id][0], 1 => $items[$id][0]);
    if (count($items[$id]) > 1) {
      array_splice($array, 2, 0, array_slice($items[$id], 1));
    }
    $items[$id] = $array;
  }
}

```
> 1 votes

# Answer
`hook_field_formatter_view()` is where your code makes the output that's shown to the user, and so it wants a renderable array as a return value. So just process the first image twice and give it a different css class or something.

Something like:

```
$output = array();
if (($field == 'myFieldType') && ($display == 'full')) {
  $output[] = renderFirstImage(reset($items));
  foreach ($items as $item) {
    $output[] = renderImage($item);
  }
}
return $output;

```

Since `hook_field_formatter_view()` expects a renderable array, and since renderable arrays are marked as rendered when they're rendered, simply making two references to the same object will cause one to be rendered, marked as rendered, and then subsequently ignored the next time.
> 0 votes

---
Tags: hooks, media, theming
---


# Question
Title: How can I make a node template that works on any url I specify?
At the moment I can make a template for a specific node based on the node id.
However I want to make the same template work off of the url or title of the node so I can use it on multiple sites for the same node which doesn't have the same node id on each of the sites.

How can I do this?

# Answer
> 0 votes
Probably best to add a template suggestion rule to hook\_preprocess\_node, to control which templates are looked for.

e.g, in template.php

```
/**
 * Implements hook_preprocess_node
 */
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'article') {
    // Regex replace anything not alphanumeric with underscore _ in node title
    $title = preg_replace('/[^a-z0-9]/', '_', drupal_strtolower($variables['node']->title));
    $vars['theme_hook_suggestions'][] = 'node__'. $title; // Use title in template suggestion
  }

}

```

Then you could use a template like

```
node--my-node-title.tpl.php

```

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


# Question
Title: Notice: Undefined index: node-readmore in theme_preprocess_node()
I am using this code on D7 for my themes template.php to replace default 'Read More' title with 'Read More →' (it just adds arrow):

```
function theme_preprocess_node(&$vars){
  $vars['content']['links']['node']['#links']['node-readmore']['title'] = str_replace("Read more","Read more →",$vars['content']['links']['node']['#links']['node-readmore']['title']);
}

```

It all works, but when clearing cache I get this error message:

```
Notice: Undefined index: node-readmore in theme_preprocess_node()

```

# Answer
Probably the page view of the node not including the read more link.

e.g

```
function theme_preprocess_node(&$vars){
  if(!$vars['page']){
    $vars['content']['links']['node']['#links']['node-readmore']['title'] = t('Read more →');
  }
}

```

or perhaps

```
function theme_preprocess_node(&$vars){
  if(isset($vars['content']['links']['node']['#links']['node-readmore'])){
    $vars['content']['links']['node']['#links']['node-readmore']['title'] = t('Read more →');
  }
}

```

No need for the str\_replace either if just setting the full text string.

Note, an alternative is to translate that text,

e.g with stringoverrides or in settings.php

```
$conf['locale_custom_strings_en'][''] = array(
  'Read more'      => 'Read more  →',
  'Old text 2'      => 'New text 2',
);

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to decrease the width of the sidebar for a specific page?
Is it possible to decrease the width of my right sidebar for any specific page only? If so, please shed some light on that.

I have created a basic page whose node id is 56. In that page I want my right sidebar region to occupy less width than it normally does. This can be done through CSS but I want to know if there is a way to do that through Drupal, either with coding or without it.

# Answer
> 0 votes
Most popular themes add body classes for the current page.

e.g, assuming page is node 56 and sidebar wrapper is .sidebar-right, in layout.css:

```
body.page-node-56 .sidebar-right{
  width:180px;
}

```

Check your HTML body tag for the available CSS classes for your theme.

# Answer
> 0 votes
You could use `drupal_add_css()` to conditionally include a custom CSS file on particular pages.

You could also add a custom template in your themes templates folder. If you clear caches after including it, it will automatically be included as long as it follows the Drupal template naming conventions.

---
Tags: 7, theming
---


# Question
Title: Undefined Index when adding a new field to any Content Type or Taxonomy
Every time I add a new field to a taxonomy or any Content type, I get this error message on the edit screen.

Notice: Undefined index: default\_image in image\_field\_update\_field() (line 439 of /var/www/html/modules/image/image.module).

I'm stuck on where to debug next. Drupal logs show this message? Other image related modules include BackgroundField. Has anyone come across this?

# Answer
> 1 votes
Sounds like an issue with your current Drupal version

> A patch to fix this has been committed to 7.x and will be available in 7.15. In the meantime, visiting the image field settings form and clicking Save will resolve the issue

More info: http://drupal.org/node/1558548
Patch here: http://drupal.org/files/drupal-1558548-3.patch

---
Tags: 7, entities, media
---


title: Create custom field programmatically

text:
# Question
Title: Create custom field programmatically
I'm trying to re-create a field in my custom form with a date-picker. A dpm of my already existing form learned me the form looks like this:

Is it correctly to assume you can create the field with following code? Because I get an empty result...

```
$form['my_field_field_periods'] = array(
    '#title' => t('Periode 1'),
    '#type' => 'container',
    '#attributes' => array(
      'class' => array(
        'field-type-datetime', 'field-name-field-periods','field-widget-date-popup')
    ),
    - and so on -
  );

```

# Answer
> 2 votes
You can add a regular select box style date field with the form api like this:

```
$form['date1'] = array(
  '#type' => 'date',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
);

```

Drupal core doesn't have a date popup FAPI element, but you can add jQuery UI datepicker to a regular text field as well

```
$form['date1'] = array(
  '#type' => 'textfield',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
  '#prefix' => '<div class="datepicker-wrapper">',
  '#suffix' => '</div>'
);

// Attach JS datepicker library and init js for textfield
$form['#attached']['library'][] = array('system', 'ui.datepicker');
$form['#attached']['js'] = array(
  drupal_get_path('theme', 'my_theme') . '/js/datepicker-init.js',
);

```

Then in your theme `/js/datepicker-init.js`

```
(function ($) {
  // Add calendar popup to date textfield
  Drupal.behaviors.setDatePicker = {
    attach: function(context, settings) {
      var options = {
        'dateFormat':'yy-mm-dd',
        'changeYear':true,
        'changeMonth':true
       };
      $(".datepicker-wrapper input").once('datepicker').datepicker(options);
    }
  };

})(jQuery);

```

The result is something like this:

---
Tags: 7, forms
---


# Question
Title: Next/Prev buttons for nodes based on nodereference field
By using this tutorial http://blog.urbaninsight.com/2011/09/12/adding-pager-navigation-nodes-drupal-7 I have created next/prev buttons for my images.

But as I have a lot of galleries and I need to filter images not only by node type but also by node reference field value.

The machine name of my field is `field_pers_gallery` and in phpmyadmin it is assigned to a particular gallery by `field_pers_gallery_nid`.

I'm note good at creating db query, could anybody help with any advices?

# Answer
> 1 votes
I don't know if you managed to get your pager working yet, but I've just modified a piece of code to create a pager based on node reference. You're free to use it as you see fit. You can go to my blog to see it:

http://www.visionarymedia.nl/blog/drupal-pager-based-node-reference

---
Tags: 7, nodes, database, paging
---


# Question
Title: Bulk editing of Fields on multiple entities
What is the best way to do the following?

* Open up a page that does a form callback from hook\_menu
* Based on a URL arg, load all entities (probably with EFQ) with that argument
* Present certain fields on the entities to edit, with one Submit button at the bottom
* On Submit, each of these are processed and saved within their respective Entities

As a bonus, it would be great if the form output each set of fields in a tabular format, like editing a grid (without jQuery plugins needed).

The first two I can do, but I am not seeing seperation of entity data in the form submit data (knowing which data goes with which entity\_id).

What I am trying to do is provide a quick way of editing game results line by line (Team A (score\_home property) vs Team B (score\_away property)).

# Answer
The Multiple forms module might point you in the right direction.

Here is a quote from its project page:

> This is an API module which lets you put several forms into one `<form>`.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: CSS not being loaded from CDN (CloudFiles)
I've got CDN installed and configured and I've copied all of my css up to the CDN.

The CSS urls change from this (using my hosts IP address):

```
@import url("http://xxx.xxx.xxx.xxx/modules/system/system.base.css?mhdfaw");

```

When I enable the CDN module, they look like this:

```
@import url("http://b24fb3007bd5cf6f616a-a6cd251ed0dfba89acb0fcd5fb378f4a.r38.cf1.rackcdn.com/modules/system/system.base.css?mhdfaw");

```

When I copy that url and paste it into my browser, the file exists and is being served by the CDN just fine. I have tested EVERY css file in the source and every single one of them exists, but my page is completely unstyled. None of the CSS files are being applied at all.

I'm not referring to the images in the stylesheets, I'm referring to ALL of the styles.

What the heck?

EDIT: Here is a link to my site, in case that helps:

```
http://108.166.112.120/blog

```

# Answer
The files had the wrong mime-type.

I wrote a php script using Rackspace's Cloud Files PHP api to upload all of my files to the Cloud Files container. All of the files had the default mime type/content type of "text/plain". I changed the content types of the css files to "text/css" and it all started working.
> 0 votes

---
Tags: 7, cdn
---


# Question
Title: Why does drupal_lookup_path() return NULL?
In a Drupal 7 site, I installed the Pathauto module. The user account I am using to log in has the permission to create new path aliases.

When I manually create a node, unselect the checkbox for automatic alias generation, and enter a custom alias (for example, *qwerty*), I can use `drupal_lookup_path()` to get the path alias.

```
$path = drupal_lookup_path('node/' . $node->nid);

```

However, using the following code in a test doesn't work.

```
$edit = array(
  'title' => 'asdf',
  'path[alias]' => 'qwerty',
);
$this->drupalPost("node/add/{$this->content_type}", $edit, t('Save'));

$path = drupal_lookup_path('node/' . $node->nid);

```

The value of `$path` is `NULL`, even when the path alias exists and `$this->drupalGet('qwerty')` returns a 200 status.

Why is `drupal_lookup_path()` failing to find the path alias only when called from a test?

# Answer
I tracked this down to the fact that `current_path()`, which returns `path/to/content` in the browser, instead returns `batch` when called from within Simpletest.

Since `drupal_lookup_path()` uses the output of `current_path()` to generate the `$cache[map]` variable that it uses to find and store the path alias, this prevents `drupal_lookup_path()` from working in tests.

I have filed this as an issue on d.o.
> 1 votes

---
Tags: path-aliases, testing
---


title: Why don't we hack core?

text:
# Question
Title: Why don't we hack core?
I couldn't believe that this question hasn't already been answered on this site, but I didn't find it when I searched, so...

## Why is it such a bad idea crime against nature to hack core?

* Is it really that great to be able to upgrade your core version? Most of my sites end up having horribly out of date cores anyway, so why bother?
* Even if it is so bad for site owners, why does the community care so much? Why is it referred to as "killing kittens"? Isn't that rather hyperbolic?
* Hacking core is so easy, don't we like taking the easier route to a problems' solution?
* Aren't there problems that can *only* be solved by hacking core? What then?

# Answer
Generally speaking, there are three reasons for not altering the Drupal core code:

* Your changes would be lost each time you update Drupal, if you don't take any necessary steps. Even in the case you create a patch for the current Drupal version you are using, the patch could not apply to the newer version, and you would need to create a patch for the new version too.
* Security fixes apply to the Drupal core as maintained on Drupal.org, but could not apply to your hacked version. That means you should check your version is not affected by the security issue raised against Drupal core.
In the case your hacked version introduces a different security issue, you are the only person you can find it, as you don't have the support of the security team that investigate on security flaws present in Drupal core code, and in third-party modules hosted on Drupal.org.
* The changes you introduce could be incompatible with Drupal itself, but also with third-party modules, which are required to work with Drupal core, not with any hacked version one can create.
Every time Drupal introduces a new feature (which still happens in Drupal 7, and in Drupal 6, although with less frequency), or a new API change, there is the chance the hacked version is incompatible with the recent changes.

That said, it is possible to create an hacked version, but that is not the task a single developer can carry, in the same way Drupal is not maintained by a single person. In fact, Pressflow is an *hacked* version of Drupal that has been created with performance in mind, and to resolve some performance issues a Drupal site could have.

> Aren't there problems that can only be solved by hacking core? What then?

Most of the times, it is possible to alter the features/behavior without editing Drupal core code. There is always a hook that allows to change the features/behaviors Drupal has, and that is the preferred method.
> 8 votes

# Answer
I could write a massive answer here, but I'm just gonna post this link: Never hack core!

The main reason I guess is that if you hack core to do something you need, and then update it...BANG! Your changes are gone. Lost. You could then try and roll back the code from your VCS, but seeing as you can't roll back database upgrades from Drupal core - you're looking at restoring all code from VCS, and then restoring databases from your backups. All the time you're trying to roll back your code, you'll probably then notice that your last pre-update database backup failed, and you'll swear more than you've ever sworn before.

Also - most importantly - if you hack core, then Dries and Webchick both kill a kitten :-o
> 13 votes

# Answer
## "What can not hacking core do for me, the developer?"

* Your site can be upgraded for security releases
* Your site can be upgraded to fix annoying bugs in core
* Your site can be upgraded to support new modules
* Your bug reports and support requests on core and contrib will be able to be responded to
* You want to use a supported CMS, that's why you chose Drupal. When you hack core, in the words of webchick, "If you hack core, congratulations! You've created your own fork of Drupal, and now you and you alone are responsible for maintaining it!"

## "What can not hacking core do for my client?"

* Your site can be maintained by someone else after you fire your client/win the lottery/get hit by a bus

## "What can not hacking core do for my community?"

* Your bug reports will actually provide useful info for the maintainer of core or contrib modules.
* If you find a legit bug in core that must be patched, the line between 'hacking core' and 'becoming a core contributor' is as fine as simply diff'ing your changes and uploading them as a patch into a relevant d.o issue. Violá! Core is better for your efforts, and your name is associated with giving back code to the community.

*Everyone's a winner when you don't hack core!*
> 12 votes

# Answer
I am currently working on a hacked core website. I have difficulties finding how something as simple as font is being set up. I also spend few days fixing a bug that was introduced by the core hack. I found it by searching for a string in the whole drupal code.

If you don't follow the standard structure of programming in drupal then how can someone else find and edit the changes you introduce? This is especially painfull because in drupal every single php file can implement a hook. Try finding out which one is causing problems.
> 5 votes

# Answer
> "Aren't there problems that can only be solved by hacking core? What then?"

To answer this question, yes, there are sometimes problems you have to overcome that mean you have to hack core (or a contrib module).

In this case I believe it is ok to hack as long as you put lots of comments in your hacked code and document everything you change.

For example, for any core or contrib change I make I create a patch. If it is generic and useful to other people I submit it to drupal.org in an issue, otherwise it is for my own use.

I then commit the patch file to my version control along with the code change.

This means that I can see by looking for patch files if something has been hacked.

In addition to that, I also add a list of hacks to the developer documentation for the site (you really should have developer documentation for the sake of others that might work on the site and for yourself when you inevitibly forget things).

In this hacks documentation I list each hack with what the hack does and why, modules/files affected, the name of the patch file that contains the hack code, and a link to a related drupal.org issue if there is one (almost always in my case there is).

Then you and whoever else works on the site in future has a full list of hacks and doesn't have to worry about accidentally breaking something with an update.

Then for the update process I check my list of hacks and have a quick look for patch files in all the modules I am updating. If there is a hack and it has a drupal.org issue, I check the issue to see if the latest version has the patch included, in which case I blow away the hack with the update and remove it from my list of hacks (make sure by looking at the drupal.org commit messages that what was committed was the same as the version of the patch you are using, or at least in functionally the same).

If the patch was not committed, all I have to do it update the modules and reapply the patches. In a lot of cases the patches will still apply cleanly and the process is easy, but sometimes you have to reroll the patches for the new version and then commit the new version of the patch to your local repository (along with posting it to the relevant drupal.org issue where applicable).

Another thing I like to do if I have more substantial patches or patches that interact with core fucntionality of a module (or just custom modules that extend on top of a drupal.org module), is to check the release notes of the updated module (that means all version in between your current version and the version you are updating to) and make sure there is nothing in there that is likely to break your code. Note: A lot of module maintainers are good these days with giving complete release notes but there are still a lot that do rubbish release notes. In this case in some cases I go through all the commit messages since my current version (this is usually only in cases where I have complex code that interacts deeply with another module). Note: In this case it might be easier to do a diff between the version you have and the new version to see what has changed.

Then, after updating (on a development copy of the site), test thoroughly. You will eventually learn what thoroughly means after a few bugs slip through.

Then when it has been tested sufficiently, upgrade the live site or push your local updates up or whatever your deployment process might be.

The reason why everyone says don't do it, even if it is easier: Because most people don't have a system like I have outlined, so when it comes time to do updates, or the site is handed to someone else to work on, it becomes a nightmare and a lot of time (sometimes an enormous amount of time) has to be spent solving bugs and tracking down hacks and working out why they are there, etc.

If you ever inherit a site like that you will fully understand :)
> 4 votes

# Answer
If you earn a living from installing and creating Drupal websites, then it's necessary to keep them up to date. If most of your sites end up being horribly out of date, then you are not professional.
> 1 votes

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


title: Feeds and pipe | separated values

text:
# Question
Title: Feeds and pipe | separated values
I am trying to use Feeds to import data from a CSV file. However, the file I've been provided with, even though its type is "Microsoft Excel Comma Separated Values File (.csv)", the values are separated by a pipe | character instead!

Will this work? Or will it corrupt the database?

The reason I ask this is because in the Select a parser section one of the options is CSV parser (parse data in comma separated value format) and that is the only one that I can see would suit me... except for my pipe separated values format ...

# Answer
This won't work out of the box because Feeds is expecting a CSV but you can convert this to a proper CSV file using the Feeds Tamper module to modify the data before passing it to feeds.

However, the easier way to do this would be to just load the file back into Microsoft Excel as a delimited file, and then export it back as a proper CSV.
> 0 votes

---
Tags: feeds
---


# Question
Title: How do you normally structure your Menus?
I am using the Sitemap module, and in order to display the pages available on the site, I need to enable which Menus are displayed. It then lists them in sections, with a Menu title above each section.

I have 5 menus at the moment, so the sitemap generated looks very messy. What is the best way around this? How do you structure your Menus so it all looks neat in the Sitemap, but is also functional?

Also, do you normally rename the Main and Navigation menus to Primary links and secondary links, or do you leave them as they are? Do you hide the Menu headings from being displayed in the Sitemap?

# Answer
> 2 votes
One option you have is to leave your menus as they are and use CSS to style the page so it appears nicer.

You can do things like reduce the amount of space between menus.

Another way (this depends on your sites menu requirements - it may not fit with what you need), is to have primary links be your sitemap. Add everything you want in your site map to the primary links, going in as many levels deep as you need. Then don't actually display all the levels in your menu (unless you want to and have deep drop down menus). Then have the site map just display the primary links menu.

This will give you a nicer looking site map.

In my opinion, site maps are something drupal does not do well (short of doing something more custom). I have never seen a satisfactory result (to my standards) from using the site\_map module.

Another option would be to use the menu\_block module, which would allow you to create a bunch of menu blocks for specific menus (and levels of those menus), which you could then position on your site map page in a grid (or whatever layout you prefer). This allows you to be very specific with what is displayed on the sitemap and how it is displayed. Menu blocks also means you can customise the heading specifically for that block, without changing the name of the menu. You could assign the blocks to a node page that has some introduction text for the body, of you could use something like the empty\_page module to add a non-node sitemap page to assign your blocks to.

You can call your menus whatever you prefer, but I would not rename them to primary and secondary links. It is better to use more semantic names. This is important in cases where you want the menu title displayed with the menu, and also when the menu title is there but hidden, to give screen readers better context, for accessibility.

Whether or not to display the manu titles in the site map also depends on your site setup and what you want to achieve. If your menus are for distinct sections of the site it might be useful to have those sections stated in the sitemap, however if the title is not really relevant, for example "Main manu", "Navigation", "Footer links" etc., then it would likely be best to not show them.

---
Tags: navigation
---


# Question
Title: How can I add code that will call the javascript within a block every minute?
I have a block that contains javascript which calls a website that sends an ad to this block (see below: Note: I changed the domain name to adserveringwebsite). How can I add code that will call the below javascript every minute so that a different ad will show up every minute instead of just one ad at page load?

```
<script src="http://www.adserveringwebsite.net/1e-kn99655"></script>

```

# Answer
> 1 votes
To throw in some old-skool, and realize it's up to you to drupalize all of this if your ad site url is dynamic, but, you could also throw all of this in a separate static file and call it from an iframe inside your block and use refresh, eg, in the file, let's say it's /minute\_by\_minute\_ad.htm:

```
<html>
  <head>
    <meta http-equiv="refresh" content="60">
  </head>
  <body>
    <script src="http://www.adserveringwebsite.net/1e-kn99655"></script>
  </body>
</html>

```

Then your block would contain something along the lines of:

```
<iframe src="/minute_by_minute_ad.htm"></iframe>

```

which would have a potentially added benefit of some speed improvements with ad loads in the iframe (debated heavily online but I've seen some).

# Answer
> 2 votes
You will need to use JavaScript's setTimeout() function:

To elaborate, place the code that calls your ad server inside a JS function.

Then, use `setTimeout()`, as demonstrated in the website I linked to, to call it at every x interval.

# Answer
> 1 votes
I think the Block Refresh module will do what you want out of the box.

# Answer
> 0 votes
Using an iframe isn't "the drupal way".

The drupal way is using AJAX to reload only the block. This is the same thing that Block Refresh does.

BUT... if you don't want the overhead of *another* module and you want to do it in your own module (I'm assuming your module is called 'mymodule' and the delta of the block is 'mymodule-delta'):

Make sure you include a javascript code, use this in your block content generation function:

```
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js', array('every_page'=>FALSE));

```

The javascript file should have something like this in it:

```
(function ($) {
    setInterval(function() {
        $('#block-mymodule-myblock-delta .content').load('/myblock', function (response,status,xhr){
            if (status == 'error'){// some error checking
                $('#block-mymodule-myblock-delta .content').html("connection lost");
            }
        });
    }, 60 * 1000); // running every 60 seconds
})(jQuery);

```

That's going to fire an AJAX call to '/myblock' and fill the '#block-mymodule-myblock-delta' element with the content.

Now back in your module, you'll need to make the '/myblock' page like this:

```
function mymodule_menu() {
  $items = array();
  $items['myblock'] = array(
    'page callback' => 'myblock_via_ajax',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function myblock_via_ajax(){
    $block = module_invoke('mymodule','block_view','myblock-delta');
    print $block['content'];
}

```

---
Tags: ajax
---


# Question
Title: Change the wording of the registration page
I want to change the wording of the default registration page. I found some posts about completely customizing/re-theming the page but they seemed like total overkill for what I had in mind.
Specifically, this is designed to be a website for only students that go to my school, so I have already set it up so that you can only register with *@myschool.edu* email address. But I can't figure out how to let people know that on the registration page. I am surprised you can't edit the registration page through the configuration module at all.

# Answer
If you just want to add a few directions at the top/bottom, try creating a custom block. Create a custom block with the instructions you want to add. On the block configuration page, you can set the path to display only on certain pages. Set that to `user/register`. Then all you have to do is make sure the block is appearing in the appropriate region in your theme.
> 4 votes

---
Tags: 7, users
---


# Question
Title: Create a view that displays only the fields from the most recent user node
To specify, I want the view to only apply to one single node and not all other nodes and only pull fields from that one particular node that was last created.
As of now the view displays all the nodes and their fields with a pager, I just want it to load content from the last node created by that user.

Can anyone suggest?

# Answer
> 1 votes
* Add a contextual filter for user
* Set pager to "none" and "number of items to display" to "1".
* Set a sort criteria to sort by date, descending.

---
Tags: users, views, entities
---


# Question
Title: i have prepared form api, now how to insert form values when i click submit button by using db_insert
I have prepared a form using Drupal form API. Now how can I insert the form values when I click the submit button by using `db_insert()`?

```
$form['totp'] = array(
    '#title' => t('Title of the Programme'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#maxlength' => 250,
    '#size' => 50,
);

$form['pd'] = array(
    '#type' => 'radios',
    '#title' => t('Programme Day'),
    '#required' => TRUE,
    '#options' => array(
        0 => 'One Day Programme',
        1 => 'Two or More Day Programmes'
    ),
);

```

The above values to be stored in MySQL table?

# Answer
> 3 votes
You would need to add a custom form submit handler.

```
$form['#submit'][] = 'mymodule_custom_form_submit';

```

Then, in the function, use `$form_state['values']`;

```
function mymodule_custom_form_submit($form, $form_state){
    db_insert('yourtable')
        ->fields(array(
            'totp' => $form_state['values']['totp'],
            'pd' => $form_state['values']['pd']
          ))
        ->execute();
}

```

---
Tags: forms
---


# Question
Title: Create a view to display last browsed content
I want to create a view to display last browsed content by the user. My site has a lot of content and I want to create a view, either a page or a block, to show the last browsed content by the user. That view should show the last browsed content first followed by rest. Say for example, content A was browsed 10 seconds ago, content B 10 minutes ago and content C was 1 hour ago, then the view should list them in the order: A B C.

Thanks

# Answer
> 2 votes
I am able to do so using the sort criteria timestamp by the Radioactivity module.

> This module provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.

# Answer
> 0 votes
This sounds like you should be using the core tracker module. This allows you to keep track of your last visited pages.

---
Tags: views, nodes
---


# Question
Title: How to add a view for a node with an ID?
I have a simple blog application and would like to add style my nodes with views. More specifically I want to style node/nid path and when I point that in the views configuration, it only works if I type: http://example.com/node/3/3
but if I type http://example.com/node/3 it doesn't work. How can I make the nodes view work with the id being pointed out only once?

If my frontpage is called /content then that would be the path I would point out in the views configuration. In this case, however, I am trying to style an opened node - t.i. where the path is node/id . Everything works fine if I type `node/id/id` in the adress bar, but not if I type `node/id` . As the path for that view I have done so: PAGE SETTINGS `Path:/node/%`

# Answer
> 2 votes
I think you'd find Panels with a node\_view panel page override suits there.

Install and enable page manager then enable the default "Node view" panel page.

It will override node/%node with a page in which you can embed views content pane displays etc...

---
Tags: views, nodes
---


# Question
Title: Problem with db_select not returning records sometimes
Works:

```
$rows = db_select('notification_queue', 'nq')
    fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method','latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method')
    ->addExpression('COUNT(*)', 'count')
    ->execute();

```

Does not work:

```
$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->execute();

```

I'm testing that something is returned with a simple foreach loop:

```
foreach($rows as $row) {
    msg($row); //msg is a simple wrapper for drupal set message
}

```

The reason I need to do things the second way is that I have to use addExpression and it won't work if try and use it in the first way.

I've tried this:

```
$rows = db_select('notification_queue', 'nq');
$rows->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'));
$rows->groupBy('uid');
$rows->groupBy('notification_type');
$rows->groupBy('delivery_method');
$rows->addExpression('COUNT(*)', 'count');
$rows->execute();

```

And I've checked that the resulting query is correct (it is, I've tried using it with MySQL directly and it does exactly what I want). However, I can't get access to the rows using Drupal.

What am I doing wrong?

# Answer
> 1 votes
Turns out addExpression does not return the object, just the alias of the expression. Solution:

```
$query = db_select('notification_queue', 'nq')
    ->fields('nq', array('created_time', 'uid', 'notification_type', 'delivery_method', 'latest_time', 'earliest_time'))
    ->groupBy('uid')
    ->groupBy('notification_type')
    ->groupBy('delivery_method');

$query->addExpression('COUNT(*)', 'num');
$rows = $query->execute();

```

---
Tags: 7, database
---


# Question
Title: How to translate Views header syntax? not Title
In a view, i have filter content using "Language". it works fine. i have added "header" contain HTML syntax (which will be shown with top of view) like:
`<div class="xyz">Text need to translate</div>`
i couldn't translate this syntax.

can anyone suggest how it will be translate??

# Answer
Here's how to translate expressions containing HTML code:

1. Go to `admin/config/regional/i18n/strings`
2. Check "full HTML" in "Translatable text formats" section
3. Then, go to `admin/config/regional/translate/i18n_string`
4. Click on "Refresh strings".
> 4 votes

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


# Question
Title: How to play the video using media module?
I am using drupal 7 and i am in need of upload a video from our local system as well as from the video. I found the media module and media\_youtube module. After installing the module, the url from the youtube is working, but for local machine system video upload in getting downloadable option in the front end and not played.

How to play the video without downloadable option in the same page. Please suggest me some ideas.

Thanks.

# Answer
> 2 votes
You can see see here the list of player modules that extend media module.
There is also basic version information about each module.

Start with jPlayer and see if it fits your needs.

---
Tags: media, files
---


# Question
Title: How to apply image style to image field in view based on the sort position of that image field?
my homepage is done with panels. Home panel contains a view that displays specifically 9 nodes that contain image field. Sort criteria is Random. These 9 nodes are in three rows each containing three. What I want to achieve is that image field of the first node in the first row would have image style: medium, second node in the row would have style: large, third would have medium again. Second row first node would have image style: large and so on.

I know there is a module to style specific nodes but this styling should be based not on the node itself but on the position it was given by the Random sort. Please see image attached.

I think it would be acceptable to shrink the images using CSS, but then each position should have it's own class, how could I go about this? Without JS li order targeting would be preferable.

Thanks a lot for your help.

# Answer
You can add a field of the type "**Global: View result counter**"

This will add a number depending on the position of the result.

You can use this to add a class using token to the image.
> 0 votes

---
Tags: media, views
---


title: Nesting of tabs within quicktabs

text:
# Question
Title: Nesting of tabs within quicktabs
is it possible to create new tabs and place them under quick tabs, i.e, i want to create two new quick tabs and add them under (nesting structure) already existing three quick tabs...How can i achieve this

# Answer
> 0 votes
I'm not sure how nested tabs can be created from QuickTabs admin UI. But I believe you can render the child tabs programmatically. The below is how to render a quicktab.

```
<?php
if(module_exists('quicktabs')) {
    $tabs = quicktabs_build_quicktabs('child_tabs'); // where 'child_tabs' is your quicktabs machine name
    print render($tabs);
}
?>

```

You can add such kind of code snippet into your view/block of a particular parent tab.

Let's say for example, you have a parent tab "Parent Tab 1" which is assigned to a block created from **admin/structure/block/add**. You could add the above code snippet into the block body.

If you enable the "PHP Filter" module, you can embed any PHP code into the block body when you select "PHP Filter" text format.

Then, when you access the "Parent Tab 1", you will see another quicktabs inside which is printed programamtically.

# Answer
> 4 votes
If I understand your request well, I think this is the solution supplied by @monymirza. But in the latest stable version of quicktabs you have the possibility to select quicktabs to be show under a tab.

Checkout this image to see : (**ab** is a quicktab instance that has been created earlier, and **c** is the parent tab that will contain **ab**)

---
Tags: views, routes
---


# Question
Title: How can I use LESS in a subtheme in Drupal 6?
I have a site with the LESS module installed. The main theme CSS, `main.css.less` uses `@import "lib.less"` to define a set of variables that I use for different text colours, etc.

Now, I want to create a sub-theme. This subtheme is identical to the main theme except `lib.less` contains different colour values for some of the variables. I set it up in the normal Drupal 6 manner. Again, I want to keep the styles, just change the colours by getting the main `lib.less` to be overriden by my subtheme's `lib.less`.

When the subtheme pulls in `main.css.less` from the main theme, it also pulls the main theme's `lib.less`, even though in my subtheme I have a different `lib.less`. I have also tried adding this to my subtheme info:

`stylesheets[all][] = css/lib.less`

To try and get it to recognise the subtheme's LESS variables, but it always brings in the main theme `lib.less`. Any ideas?

# Answer
I am looking for a cleaner answer to this as well but I have found I need to create a main.css.less file in the subtheme and copy all the references which use the new subthemes variables (lib.less) and then they work.

Without copying the main.css.less into the subtheme the new variables don't work.

Maybe this is the correct way, but it doesn't feel right to me.
> 0 votes

---
Tags: 6, theming
---


# Question
Title: Pinterest-style image presentation page?
Any Ideas how to create pinterest style image presentation page(view)?

Basically, it is like a page that have images in columns, images in each column have same width but different height.

# Answer
> 4 votes
For that, you need to use Masonry jQuery plugin. With Drupal you've this module but it's not available yet for Drupal 7.x, so you should either make your own template with the plugin or try to port the mentioned module into Drupal 7.

# Answer
> 0 votes
I've created a small module for making pinterest-style galleries with Drupal. It's in a sandbox at the moment here: http://drupal.org/sandbox/MarkConroy/1903438

You can see a demonstration of it here: www.adesignforlife.net/pinterest-galleries \- click on any gallery to see the images also in a Pinterest style.

It basically uses the masonry js library and adds some CSS to the images.

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


# Question
Title: drupal_set_message on node edit page shows twice with theme hook
I want to display a value of a field which the user has no access to in a dsm when the user edits the page. The dsm is showing up after saving the node, and while that's fine (I'd even consider it a feature) it's showing the before-edit value of the node.

I believe I've run into this problem but there doesn't seem to be an easy fix. Here's a look at the `template.php` function.

```
function themename_form_vakature_node_form_alter(&$form){
    if(isset($form['#node']->field_vacature_scheduled_for_unp)){
        if($form['#node']->field_vacature_scheduled_for_unp['und'][0]['value']){
            $expirydate = date("F j Y",$form['#node']->field_unpublish_date['und'][0]['value']);

            if($form['#node']->field_unpublish_date['und'][0]['value'] < time()){
                drupal_set_message(t("This vacature has expired."),'status',FALSE);
            }
            else{
                drupal_set_message(t("This vacature will expire at: ").$expirydate,'status',FALSE);
            }
        }
    }
}

```

Basically, the message displayed on the edit page is repeated after a save. I need it to either not repeat or show the correct updated information.

# Answer
Form alter changes the form when it's being built for display.

If you want to use the value on the node after update, use a hook like

instead.

To tweak your code snippet, something like:

```
/**
 * Implements hook_node_presave
 */
function mymodule_node_presave($node){
  if ($items = field_get_items('node', $node, 'field_vacature_scheduled_for_unp')) {
    $vacature = reset($items); // Use first field item value
    $expirydate = date("F j Y", $vacature['value']);
    $items = field_get_items('node', $node, 'field_unpublish_date')
    $unpublish = reset($items); // Use first field value
    if ($unpublish['value'] < time()) {
      drupal_set_message(t("This vacature has expired."), 'status', FALSE);
    }
    else{
      drupal_set_message(t("This vacature will expire at: "). $expirydate, 'status', FALSE);
    }
  }
}

```
> 0 votes

---
Tags: theming, forms
---


title: What does 'set breadcrumb' do in Rules?

text:
# Question
Title: What does 'set breadcrumb' do in Rules?
One of the actions that comes with the Rules module is 'set breadcrumb'.

When trigger this action, however, nothing seems to happen to the breadcrumb.

What is supposed to happen? Does it set the breadcrumb on the page that the user was on when it was triggered, or on the page whose path is used in the action? Why isn't it doing anything, or is it doing something, and if so, what is it doing?

# Answer
> 1 votes
To use the "Set breadcrumb" rules action you should add it to the event "Content is viewed", for example

1. Event: Content is viewed
2. Condition: Content is of type article
3. Action: Set breadcrumb: Title: Articles\n\[node:title\] Paths: articles\n\[node:url\]

rules\_action\_breadcrumb\_set basically goes through those title and path values and uses drupal\_set\_breadcrumb to set the breadcrumb.

---
Tags: rules, breadcrumbs, actions
---


# Question
Title: Path to inline image <img> inside page.tpl.php to theme/images/ dir?
Simply pasted to page.tpl.php doesn't work. It doesn't find the image and requires full path.

I know I've seen somewhere some PHP code which sets full path to image inside the theme's dir.

# Answer
> 0 votes
The following code will get you the path to your theme, together with your site's base path:

```
<?php print base_path() . path_to_theme(); ?>

```

Meaning that you should use something like this:

```
<img src="<?php print base_path() . path_to_theme(); ?>/images/your-image.jpg">

```

*Note:* the `path_to_theme()` will not have the trailing slash, so you have to add it yourself if your image is in a subfolder.

---
Tags: 7, media, theming
---


# Question
Title: Drupal 7 - View listing Organic Groups AND content within that group
I'm trying to create a view that lists all of my Organic Groups on a page AND lists the content within that group. Specifically, I would like to show image fields that have been posted to each group.

Any ideas on how I can achieve this? I can't seem to get the relationships right.

Thank you in advance!

# Answer
> 1 votes
You can create a view that listas all content (filter by your choice), make sure you include the field **Content: Audience group** (og\_group\_ref).

Then you can go to Format \> Format \> Settings (style\_options) and group by that field.

---
Tags: 7, views, organic-groups
---