# Question
Title: Is there anyway to cross reference a view?
I have View1 where I would like to add a filter which stops any rows appearing if there are rows in View2.

I thought I would have been able to execute some PHP as a filter, but I can't see any options for that.

Is there any way to use another view as a filter?

# Answer
For this you could use the advance option of the view where you could add the contextual filters and relationships.
This would help you in filtration.

For php filtration you could use the Views PHP module; that would help you in your filtration.

> This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

For information about how to use the module you could refer to README.txt of the module.
> 1 votes

# Answer
Your can also filter your view programmaticly with hook\_views\_query\_alter

Example:

```
function custom_views_query_alter(&$view, &$query){

  switch ( $view->name ){

    case 'view1':

      $view2 = views_get_view( 'view2' );
      $view2->set_items_per_page(0);
      $view2->execute();

      $custom_query = array();
      foreach( $view2->result as $row ){
        $custom_query[ $row->field_custom ] =  $row->field_custom;
      }
      $query_nids = implode(',', $custom_query );
      if( !$query_nids ) $query_nids = 0;

      $query->where[0]['clauses'] = array(
        'node.nid IN ('. $query_nids .')'
      );
      break;
  }
}

```

It's a D6 example, need some ajustments for D7

in D7 looks like :

```
$query->where[1]['conditions'][] = array(
  'field' => 'node.nid',
  'value' => $query_nids,
  'operator' => 'IN'
);

```
> 1 votes

# Answer
Use views php module to have a filter based on custom PHP code; use PHP to filter out any row.
> 0 votes

---
Tags: views
---


# Question
Title: Display Youtube videos in a gallery of thumbnails with a primary player
I'd like to be able to display a gallery of youtube video thumbnails underneath a primary Youtube video "player" area. When a thumbnail is clicked, that video would play in the main player area without the user being taken to any other page. Is there a way I can accomplish this with existing modules and/or Views?

Thanks!

# Answer
> 2 votes
I have make something like this using views slideshow.

* Added youtube thumbnail in the views
* Added youtube video in the views
* Add slideshow as style format of the view
* Set youtube thumbnail in pager of the slideshow

Its working for me.

# Answer
> 0 votes
I make something like that using javascript

1. I make a block view that display all youtube thumbnail I need
2. I will rewrite the results of the image and make a rel attribute that contains the youtube url
3. make a block view that display the first youtube video
4. using javascript change the src of the youtube object to the rel attribute in the image when I click on it

# Answer
> 0 votes
1. Install a module named youtube in your drupal website and other modules required to upload a video.
2. create a VIEW-BLOCK.
3. in the FIELDS tag,add the TITLE of the VIDEO, and also the content-name of the field which has video "VIDEO". 4.in the FILTER CRITERIA ,add the content type which you want to be displayed.
4. place the BLOCK in the region where you want the list of vides.

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


# Question
Title: Does unset($form['field']); in hook_form_alter stop entity reference views select list queries from running?
I have a slow load time in a node form and I suspect the reason is that I am populating entity reference select lists using views & therefore a number of queries are being run to populate those select lists when the form is loaded.

As most of the entity reference fields don't need to be on the node-add form but only the node-edit form I tried using unset($form\['field'\]) and hook\_form\_alter to remove those fields from the $form array but there is still a slow load time.

Could it be that the fields that get unset in hook\_form\_alter are still running their views queries?

Thanks very much and have a great day!

# Answer
> 3 votes
**Short Answer:** Unsetting the form element won't stop the view from being called. You may want to use an autocomplete widget instead if that is an option (if only to test your theory is correct - that the views are slowing the page load).

**Long Answer:** When `hook_form_alter` is called, what you get is a form that contains elements from the Field API. Modules such as Entity Reference typically do not create new Form API elements - instead they provide field widgets.

Such modules contain code that generate their widget using the base elements in the Form API. This is typically done when field\_attach\_form is called, and it is at this point that the view would be called.

This is done *before* `hook_form_alter` is called. So what you get in form alter is the low level Form API elements - not the high level widget. Unsetting the field won't make a difference, since the low-level elements that contain the list of options have already been created.

It is possible that some module would actually use hook\_form\_alter to populate their widget - I have seen this done, and must say it is very bad practice - but I do not think this is the case with Entity Reference.

---
Tags: forms, performance, entities
---


# Question
Title: how to overreide page.tpl.php with my custom menu
I have override page.tpl.php with my new custom menu created in my custom module. my menu look like below

```
$items['node/edit/restaurant/%/barcodes'] = array(
    'title'=>'Barcodes',
    'menu_name' => 'barcodes',
    'description'=>'Barcodes',
    'page callback'      => 'drupal_get_form',
    'page arguments' => array('leo_MSTag_barcode', 5),
    'access callback'=>TRUE,
    'type' => MENU_CALLBACK,
  );

```

I already try with `page--barcodes.tpl.php`, `page--node--edit--restaurant--barcodes.tpl.php` but not work for me. any new template suggestion for override mu menu page?

# Answer
I guess you could do something like this:

```
function MYMODULE_preprocess_page(&$vars) {
  $patterns = 'node/edit/restaurant/*/barcodes';
  if (drupal_match_path($_GET['q'], $patterns)) {
    $vars['theme_hook_suggestions'][] = 'page__node__edit__restaurant__barcodes';
  }
}

```

That would let you use `page--node--edit--restaurant--barcodes.tpl.php` after a cache clear.

As an aside, your `page arguments` are wrong in the router item, should be:

```
'page arguments' => array('leo_MSTag_barcode', 3), // <-- Index of arg is 3, not 5

```
> 0 votes

# Answer
You can use themeName\_preprocess\_page in your template.php.

Check the below url.

http://drupal.org/node/1089656.
> -1 votes

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


# Question
Title: how to found out if a custom hook_cron has been run?
what is the best way to find out if a custom hook\_cron which runs automatically , has been run? I did use drupal\_set\_message and watchdog but they weren't suitable for automatic crons.

# Answer
> 2 votes
When Cron runs, it leaves a message in the next table: Reports -\> Recent log messages.

If you want to know if a specefic hook has been run, you could try an experiment. For example, you could create a variable called module\_variable with value 0 in your database table and increment this value each time the hook is run.

---
Tags: cron
---


# Question
Title: Does having more enabled modules make the site slower?
Does having more enabled modules make the site slower?
I have installed 30 modules for my site, and I am afraid that it will become too slowly.

# Answer
> 11 votes
Having more enabled modules makes the Drupal bootstrapping slower, as more files are loaded and parsed. Apart that, having more enabled modules doesn't automatically mean to have a slower site, as not all the modules execute code for every requested page.

For example, if you have installed Views and you only enabled the front page view, Views will not be executed when the requested page is a node page. Although, the Views module implements `hook_menu_alter()`, and that is executed even if you have not enabled any view, but the Views module is enabled. Any implementation of `hook_menu_alter()` is invoked when the menus are rebuild, and that doesn't normally happen on every page request.

# Answer
> 15 votes
Yes. However, 30 is nothing to worry about. You're in trouble when you go over 100 ;)

Install a bytecode cache (APC or XCache) to eliminate most of the slowdown of including many files, and make sure to periodically remove unused modules (usually every project gathers modules that get unused at some point during development)

# Answer
> 1 votes
In complement to both responses of @Bojan Zivanovic & @kiamlaluno which are right you should care about module interactions. Having a lot of modules increase the risks of bad **modules interactions** (like drug interactions). I would say having more than 50 modules becomes dangerous, and that you should check early that you do not use several modules for the same task domains.

As an example building pages with blocks, views, panels, fields containing views, blocks containing views, blocks containing panels containing views containing ... The idea is to get something that a normal brain can understand (how do my different pages are composed). This can have big impact on performances when several complex loading behaviours are hidden and chained. Another example is adding several ACL rules from several modules for each content.

If you fear for performances, always use **profiling** modules and track differences after each new module addition. Sometime a small hook with some SQL inside or a custom template will save your website time generation.

# Answer
> 1 votes
three things to keep in mind during site building that can speed up your drupal site are:

1. Reduce the number of modules
2. Check your mySQL query log for slow queries and tweak code / add indexes as necessary.
3. Caching (and hoping most of your users are not authenticated)

and regarding the module part obviously greater number of module slower the speed will be, as they required a larger RAM to process..

still 30 to 60 module wont be affecting your site so much .

the ration for time of site loading and number of module is like 100 module ll delay the site by 350ms to 650ms .

hope for u next site you wuold be keeping those points in mind..:)

---
Tags: 7, performance
---


# Question
Title: Send the email when specific node is created
In one of my module, i have created a checkbox on user account page. If user has checked that checkbox at that time an email is sent to all the user when any specific node is created. Lets say when any article node is created then all the users who has checked the checkbox will be notified by the email when node is posted.

Now for the scenario given below:

1. Lets say if my site has 1000 users who has checked the checkbox/
2. Simultaneously 10 users are creating the node.
3. When only 10 users are creating the node simultaneously 1000 * 10 = 10000 emails will be sent at time.
4. I am not sure whether site will able to handle it or not.

So i want the suggestion that is there any way to queue email and send them after certain intervals like 1000 mails after an hour, 1000 after second hour 1000 after 3rd hour and so on. Or any other nice solution.

# Answer
I've never used it but the Queue Mail module purports to do exactly that:

> Queues email sending from your site so that instead of being sent immediately it is sent on cron.
>
> Useful for high traffic sites that can send a lot of emails on individual page requests.

It has the unusual properties of being both actively maintained, and bug report free at this time - so looks quite promising
> 1 votes

---
Tags: emails, queue
---


# Question
Title: How to use value passed to views_embed_view as a filter?
I want to embed a View in a node template. I understand that I can use views\_embed view to do that, and pass values to it.

```
$my_arg = $node->nid; //the nid of the node that I want to use as filter
print views_embed_view('my_test_view', 'block_2', $my_arg);

```

How can I use that value as a filter ? I want that view to list nodes that have a field with the same value as the passed to the function

# Answer
> 5 votes
The value you pass as last argument to `views_embed_view` is not passed to the Views' *filters*, but to the view's *contextual filters* (also known as *arguments*). Contextual Filters are like filters, expect they take external input (from the URL when viewed as a page or from the arguments passed to functions such as `views_embed_view`). You can learn more about contextual filters here: http://drupal.org/node/1578558

# Answer
> 0 votes
As mention by Alfred Armstrong, I needed to have to have a contextual filter that accepts the field value. From there, it was good to go.

---
Tags: 7, views
---


# Question
Title: Is there a way to send password to the user through 'Welcome (awaiting approval)' email?
I am working on a Drupal site where, i want to send an email to the user providing him with the password. Is it possible.....?

# Answer
Even better, no custom coding: check out the RPT module.

From the description:

> This small module provides token \[user:password\] during user registration. Site administrator allowed to customize the text of the e-mail that is sent to the user after registration.
> 1 votes

# Answer
Dig into these modules and you'll find something worth (quotes included are from their project pages):

* Subscriptions:

> ...enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.
* Notifications:

> ... This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.
> 1 votes

# Answer
i dnt have exact idea about how to solve the issue just seen this text

"Drupal 7 Core itself, doesn't allow to send Mails with the generated password for the User. As @webchick told in the specific issue: http://drupal.org/node/660302#comment-2592510 it would be OK to have a contrib module, to provide this again.

So in the user.module, the $account-\>password is still set, but no token for it is generated.

I thought about a single module, for this functionality, but I think inside of loggintobogan it is a lot better.

Attached a patch, which adds the token, so that it can be used inside of the mail with "\[user:password\]"

on the link http://drupal.org/node/1165126 hope this would be helpful
> 0 votes

# Answer
The Registration Password Token module provides a token \[user:password\] during user registration. Since the site administrator allowed to customize the text of the e-mail that is sent to the user after registration, you can insert this token in the welcome email.

Caveat: Sending passwords with unencrypted email is a security hazard. This is why Drupal does not provide this function out of the box (as noted by senior core developer webchick: http://drupal.org/node/660302#comment-2592510).
> 0 votes

# Answer
You cannot get the user's password from what Drupal saves in the database. Drupal doesn't encrypt the password and saves it in the database, but it saves in database the hash of the password, which is the value returned from a one-way function; this means that is not possible to calculate the value that originated the hash. That is the reason why hashes are saved instead of the passwords: If somebody access the database used by a Drupal site, it is not possible to retrieve the passwords, and access that site as one of the users registered in that site.

but to invite all the user through mail i thnk you can implment it through a custom module by:

1. Implement hook\_cron, this would builds an array containing all emails that match the criteria of your choice.

Loop through the array and send the emails via drupal\_mail.
> 0 votes

---
Tags: emails, users
---


# Question
Title: Overriding a view with views_pre_render. How to be more specific?
I have a view which has a page display and a block display. I'm trying to write some custom code that takes one of the fields from the block and uses it to amend the title of the page. So far, here's my code:

```
function custommodule_views_pre_render(&$view) {
  if ($view->name == 'topic_page') {
    $title = $view->result[0]->node_title;
    drupal_set_title($title);
  }

```

I managed to pinpoint the field I need by looking through the returned views result array. The problem is that there are multiple results arrays returned - one for each display, so there's two $view-\>result\[0\] in this view. The code above only happens to work for me because the one for the block is returned after the one for the page.

So in the interests of making sure the code doesn't break should another display be added to the view, and therefore having *that* display's result\[0\]-\>node\_title become the one that overrides the page title, how do I increase the accuracy here? How do I pinpoint my block display?

(I realise there are plenty of contrib modules that can do this for me, but I'd really like to do this with custom code as something of a learning exercise.)

# Answer
> 4 votes
You should be able to put in logic like

```
if ($view->name == 'topic_page' && $view->current_display == 'MACHINENAMEOFBLOCKDISPLAY') {
  // do whatever you want whenever Views is crafting up this view and display
}

```

which will further filter to a specific View as well as display.

---
Tags: views, blocks
---


title: Single menu link not translating

text:
# Question
Title: Single menu link not translating
I am working with a site which uses many different languages. When switching languages there is always one main menu item which doesn't translate, but the title on the page it links to does translate (menu title and page title are both the same).

The main menu mostly consists of a number of links to taxonomy terms, but this single troublesome link is to a node.

What is going wrong here?

# Answer
did you translate the site using any module

go for Content Translation core module: http://drupal.org/documentation/modules/translation
> 1 votes

---
Tags: 7, routes, i18n-l10n
---


title: Complex Content Type, modules?

text:
# Question
Title: Complex Content Type, modules?
I've been trying to figure out how to create a content type "a course" that has title, description, duration, instrucor details and contains video lessons. I made three different content types - courses, videos and instructors but couldn't figure it out how to relate it. I've been trying with View but if someone could suggest module/tips how-to would be much appreciated.

BR, Ivan Ivanov

# Answer
Entity Reference

> Provides a field type that can reference arbitrary entities:

To your course content type add new field of entity ref type and refer videos content type. Add second field to your course ct and refer instructions content type.

When you create new course you will be able to select instructions and videos

Tutorial (simple)

Youtube tutorial
> 4 votes

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


# Question
Title: show/hide field based on user's attribute
how do I show/hide field of the form based on currently logged in user's field? my users' profiles have `start_date_field`.

my form has 5 questions:

```
day_1_activity -> drop down
day_2_activity -> drop down
day_3_activity -> drop down
day_4_activity -> drop down
day_5_activity -> drop down

```

Now I would like to do a simple comparison:

`start_date_field` of logged in user with `current_date`.

if `start_date_field = current_date` show `day_1_activity` only.

if `start_date_field + 1 = current_date` show `day_1_activity` and `day_2_activity` only.

...

# Answer
> 2 votes
First you need to hide all questions drop down fields by setting `#access` to `FALSE` then show each field according to the condition.

You should use `hook_form_alter` to alter your `entityform` form.

```
function MODULE_NAME_form_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {
  global $user; // to get the current user uid

  // hide all drop down
  $form['field_day_1_activity']['#access'] = FALSE;
  $form['field_day_2_activity']['#access'] = FALSE;
  $form['field_day_3_activity']['#access'] = FALSE;
  $form['field_day_4_activity']['#access'] = FALSE;
  $form['field_day_5_activity']['#access'] = FALSE;

  // load user
  $account = user_load($user->uid);

  // get user start_date_field value
  $user_start_date = $account->field_start_date_field['und'][0]['value'];

  // show question drop down based on the condition.
  switch ($user_start_date) {
    case date('Y-m-d'):
      $form['field_day_1_activity']['#access'] = TRUE;
      break;
    case date('Y-m-d', strtotime('+1 day')):
      $form['field_day_1_activity']['#access'] = TRUE;
      $form['field_day_2_activity']['#access'] = TRUE;
      break;
    case date('Y-m-d', strtotime('+2 day')):
      $form['field_day_1_activity']['#access'] = TRUE;
      $form['field_day_2_activity']['#access'] = TRUE;
      $form['field_day_3_activity']['#access'] = TRUE;
      break;
  }
}

```

---
Tags: 7, forms, entities
---


# Question
Title: Converting Term names with special characters to Term ID's in Views
I have a view where I want to use multiple termID's as arguments. I want to use a term name from the url and convert it to a termID. I've managed to do this easily enough and it works with simple 1 word terms or even multiple words by checking the 'Transform dashes in URL to spaces in term name arguments'

I have a few terms that have special characters eg: "news & politics".

Is there any way to have nice URL's (news-politics) and get views to recognise the correct term and convert it to the correct termID? Will I have to urlencode the ampersand? Will that even work?

Edit: You can setup path aliases for single taxonomy terms, but is a problem when you want to use the term name as a second argument in a path with multiple arguments eg:

Say I wanted to filter the view results by %1 News term then %2 News & Politics

/news/news-politics

second term would not be recognised.

# Answer
You can use pathauto to set up automatic aliases for your taxonomy terms. Pathauto will take care of invalid url characters for you when it creates the automatic aliases. Then in your view use term id as the argument. The path of your view can either be taxonomy/term/% or the autoalias you set up/%
> 2 votes

# Answer
Due to a long-standing bug in the Views module reported at Issue #672606: Plus signs, dashes, and forward slashes (+-/) break arguments on Drupal.org, it is not possible to use as arguments (or "contextual filters" in more recent parlance) term names that contain certain special characters. A couple of workarounds are proposed there:

1. Use something like Computed field (computed\_field) module to create a URL-friendly field value on the term entity that *can* be used as an argument. Just be aware of the (slim?) chance of very similar terms clobbering each other if you aren't careful about uniqueness.
2. Simply use term IDs for the arguments and create path aliases for them using View Alias (view\_alias) module.
> 2 votes

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


title: Creating a Form Uploader?

text:
# Question
Title: Creating a Form Uploader?
Sorry if this an extremely newby question but I am a beginner and still trying to learn how to navigate through the site. Anyway, I am trying to create a form uploader. For example, I want someone to go to their profile page, hit upload, and then a form with 5 or so fields come up where they can fill things out and then upload it to the main content page.

Here is a use case that I am thinking of: I have a picture that my little sister drew, and I want her to add a description, the title of her picture and date it. When I hit upload there will be a upload image field and three text fields for the title, date and description. Then I want it to display on the homepage.

Sorry if that was a really tedious description for a really simple function. I appreciate all the help though! Thanks in advance for all your time and help.

Pete

# Answer
> 1 votes
The simplist way is to give your users permission to add a node. This would be done through admin/people/permissions.

To get a node to automatically appear on the front page, the publishing options for the content type need to default to 'Promoted to front page'. Set this up when you are creating your content type.

If you want to create a custom form, the method (perhaps not for newbies) is:

(1) Create a module (.INFO and .MODULE files).

(2) Implement hook\_menu (in your new module) to create a url and page where the form is to reside.

(3) Add a function to render the HTML of the form using drupal\_get\_form.

(4) Add a form builder function and construct your form using an array called $form (see form API for details).

(5) Add a submit button at the end of your form.

(6) To make the form look the way you want it to there are several methods: (i) create a theme function to add to the elements of $form; (ii) use #prefix and #suffix properties to add additional HTML and CSS ids/classes to the rendered form; (iii) manipulate the many ids/classes, rendered by drupal\_get\_form, with CSS; (iv) use the #markup properties to add additional HTML and CSS ids/classes to the rendered form (not recommended).

(7) Add a validation function, if needed.

(8) Add a submit function using node\_save (for nodes) and drupal\_write\_record (for fields) to insert your form values into the relevant database tables: node, field\_data\_field\_my\_field etc.

---
Tags: media, forms, files
---


# Question
Title: Module's new release not showing link to download
I created a new branch for a module I co-maintain, today. I followed the instructions and the branch is showing up. But, the problem is that the download links and dates are absent.

How do I create them? What extra work needs to be done?

# Answer
> 1 votes
Drupal.org automatically create download file for the module's revision, so you need to wait for the same.

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


title: Approving Pending Userpoints

text:
# Question
Title: Approving Pending Userpoints
I'm developing a site that allows users to earn points based on site actions. I have the site working for users and their points earned are going into a "pending" category. The next step is that the points need to be administratively approved.

I was trying to find a way to have this action work through a page content or onclick button without having to go through config -\> points -\> moderation.

If anyone has any ideas or thoughts that have worked for them I'd love the help, I've been stuck on this for a few days now.

Thank you!

# Answer
you can try rules module to achieve this. Create a event like "when a node is saved" and provide some condition if required and then action like grant/deduct user points. User points is integrated with rule.
> 2 votes

---
Tags: userpoints
---


title: Slideshow module

text:
# Question
Title: Slideshow module
I am looking for a slider module that can achieve sliding four video nodes at a time

Have already tried with Views slideshow (managed to do it but with only one video at a time not four as below), FlexSlider (requires image field, I do not have) and jCarousel (do not provide with a touch event). Any suggestions or tips are much appreciated.

# Answer
You can do it Views slideshow. In Views slideshow settings, use "View Action Advanced Options" and add 4 "Items per slide". see screenshot.
> 4 votes

# Answer
Could try with :

1. **Dynamic display block** : This slideshows are mainly used to showcase featured content at a prominent place on the frontpage in an attractive way. A featured content slideshow can contain e.g.: New articles, Most popular content, New products, Portfolios, Videos etc Refer from http://drupal.org/project/ddblock
2. **Feature content slider** : This is a module to feature latest nodes in a block that displays as a slideshow. This makes a featured slideshow out of node content displayed in the block. With this module, you can control options like fade, auto-rotate, speed etc. This module can be associated with multiple content types and be configured with multiple blocks Refer from http://drupal.org/project/content\_slider
> 1 votes

# Answer
You can try with jCarousel module. Here is a quote about it (from the module's project page):

> ... allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
>
> Features:
>
> * Built-in Views support.
> * AJAX-loading of additional items as needed.
> * Carousel pager/navigation to jump between multiple pages.
> * Circular wrapping of items.
> * API for direct usage of jCarousel without Views.
> 0 votes

---
Tags: 7, javascript, views
---


# Question
Title: Can original text be edited in translate interface or elsewhere?
When translating strings in the translate interface, I would also like to be able to edit the "original text" (for the default language), and not only fill in the translation strings for other languages.

Indeed, it's no secret you regularly have to modify or improve the text of a website pages. If the website is multilingual, each time you make such a change, you have to do all this foe each piece of text :

1. recreate the translation set by reloading the involved page/template in the desired language
2. find and delete the initial translation set in the translate interface
3. refill the new translation set with the same translation as the original one in the translate interface

It would bee so much easier to be able to edit the original source text of the initial translation set...

Maybe I'm missing this feature somewhere... can anyone help me on this ? Thanks you so much for your answers.

# Answer
You can use the String Overrides module to change the original strings.

Here is a quote about it (from the module's project page):

> Provides a quick and easy way to replace any text on the site.
>
> Features
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: Dynamically change email recipient in webform based on dropdown list
I have a reservation form for booking restaurants. All restaurants are added dynamically into the webform using Webform Views Select.

When the user selects resturant1, that restaurant should get an email of the reservation. Restaurants are nodes and, when I add them, I add an email field too, so this is in the database. But still I can't figure out how to make this work.

I know I need to use rules but I'm not really sure how to set it up.

# Answer
I assume the view you are using creates an option list of key|value pairs of the form **nid|Restaurant name**. For this answer, I will call your select element **restaurant**.

1. Install and activate the Webform node value module. This is a new module, and you will have to apply this patch. (If you are not familiar with patches have a look at Applying Patches.)
2. Edit your webform, and under *Form components* create a "Hidden" webform element called **send\_to\_email**.
3. Under *E-mails* add Component value: **send\_to\_email** as the *to address*.
4. Under *Form settings* go to the bottom and open the *Set Value From A Node* group.

* The *Path To Node* is **From webform field**.
    * Since the key returned is nid, set the *Path Alias Prefix* to **node/** so the nodes can be found using node/nid as the path.
    * The *Webform Source Field* is **restaurant** (your select element).
    * If the field containing the email address of the restaurant is $node-\>field\_email, set the *Node Source Field* to **field\_email**.
    * The *Webform Target Field* is **send\_to\_email**.
> 2 votes

# Answer
As you setup the outgoing mails with the webform module, you can select another webform field value as the source for the recipient of the outgoing email.

As you have select options, the value of the field needs to be the email and the title the name of the restaurant.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Why is drupal not changing the value when renderd after value change in preprocessor?
I wrote a preprocessor for one of my views but when i change the title value the value in my view keeps the same! But dpm show the right modified title. Why is that...do i have to save something somewhere?

```
function mytheme_preprocess_views_view(&$vars) {
    if (isset($vars['view']->name)) {
        $function = 'mytheme_preprocess_views_view__'.$vars['view']->name;
        if (function_exists($function)) {
            $function($vars);
        }
    }

function mytheme_preprocess_views_view__myviewname($vars) {
    //alter here that specific view
    $vars['view']->result[0]->field_field_title[0]['raw']['value']="Newtitle" ;
    dpm( $vars['view']->result[0]->field_field_title[0]['raw']['value']);

}

```

# Answer
> 4 votes
You need to pass `$vars` in by reference:

```
function mytheme_preprocess_views_view__myviewname(&$vars) {

```

# Answer
> 2 votes
or return `$vars` in mytheme\_preprocess\_views\_view\__myviewname()

```
function mytheme_preprocess_views_view(&$vars) {
if (isset($vars['view']->name)) {
    $function = 'mytheme_preprocess_views_view__'.$vars['view']->name;
    if (function_exists($function)) {
        $vars = $function($vars);
    }
}

function mytheme_preprocess_views_view__myviewname($vars) {
    //alter here that specific view
    $vars['view']->result[0]->field_field_title[0]['raw']['value']="Newtitle" ;
    dpm( $vars['view']->result[0]->field_field_title[0]['raw']['value']);
    return $vars;

```

}

---
Tags: views
---


# Question
Title: Tabular data in Drupal: create a field with multiple attributes
**Hello again**

What I want to do is simply like creating tabular form, that the user can edit attributes of each row.

In detail, I have a content type lets call it Website, this content type should contain predefined Stages and Processes. For each Stage/Process the user should be able to check as done, or enter a reference or notes, or any another related operations.

***As an Examples***

Feed the cat ---- (checkbox) ---- Reference ---- Notes

**So, how could I represent this tabular form in Drupal 7?**

**Is there any module specially made for this purpose?**

Hope you can help guys

Best and peace

# Answer
You should look at the Field Collection module, which allows you to make groups of fields and reuse them in a content type like a single field. So in your case, each collection might contain the fields "stage," "completed" (checkbox), "reference," and "notes," and then you could use that field collection multiple times throughout your content type.
> 9 votes

---
Tags: 7
---


# Question
Title: Modify Drupal error handler without killing kitten
Drupal 6's `common.inc` file includes:

```
  // Set the Drupal custom error handler.
  set_error_handler('_drupal_error_handler');

```

If I'm following the logic correctly, this results in all PHP errors going to Watchdog (if enabled).

**I'd like to continue using Watchdog** (not syslog or similar modules) for everything but PHP errors. PHP errors should go to a file (i.e., the `error_log` that is configured in `php.ini`).

I'd prefer not to patch Drupal to remove its use of `set_error_handler()`, so I'm looking for some ideas. Perhaps I can make my own call to `set_error_handler()` in a `hook_init()` or `settings.php`? Any ideas?

# Answer
Yes, you can use your own error handler instead. You'd put this in your own module - I'm not sure if you would need to put it earlier than `hook_init()`, though, i.e. in `hook_boot()`. Check out the Devel module, which has an option for overriding the error handler to make debugging easier.
> 5 votes

# Answer
```
/**
 * Implements hook_init().
 * Drupal sets an error handler that sends PHP errors to watchdog. Undo that.
 */
function mymodule_init() {
  restore_error_handler();
}

```
> 0 votes

---
Tags: 6
---


title: How to link to a translated node?

text:
# Question
Title: How to link to a translated node?
I am using Entity Translation module.

My Basic Page content type is using field translation, and I create a node (mysite.com/node/1 for English, mysite.com/de/node/1 for German).

Now in the body field of another node, I hyperlink some text to 'node/1'. But if I am viewing the site in German and I click that link, it reverts back to English.

Is the answer to provide a translation for the body field, hyperlinking to 'de/node/1' instead? I guess this would work, but seems like a lot of extra work for content editors?

Or am I missing something easy? I tried using Path Translation module (part of i18n package), but it doesn't recognise 'de/node/1' as a valid path.

# Answer
As usual, there is a module for that! :) Check out Multi-Language Link and Redirect (MultiLink). It was a bit buggy when I was testing it 5 months ago so I didn't include it in my Drupal 7 Multilingual Sites book (well, it's referred to in the appendix, page 112), but it should be working by now. Have fun!
> 2 votes

# Answer
As Kristen says, the MultiLink Filter will address that problem, in fact it was designed specifically to address the issue you describe. If you have English content at node/1 then the German version **must** be at another node (node/2, whatever.) So (without using MultiLink) where in English content you include a link to node/1, the German version would have to contain a link to node/2. That can result in a **lot** of extra work for content editors, as you say.

Another module you might want to investigate is Language Sections. That provides a way of storing multiple language content in a single node (or any other text field, such as a custom block.) But it is not a complete solution, since it only deals with text, not other fields such as node title.
> 2 votes

# Answer
I'm using Entity Translation, and had good luck with http://drupal.org/project/pathologic. The project page says there are still some issues with multilingual sites, what I did is stick to linking internal paths only (like /node/1) which is probably the least complex use case, and it worked fine.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Is it possible to hide menu items based on path?
I am looking to hide a menu item based on the path of a couples pages. It would be similar to how blocks can be shown on or not shown on a path. My initial attempts revealed that the caching of menus does not permit one to have the ability to remove menu items per page load.

hook\_menu\_alter() only runs once after a cache clear and then the menu is retrieved from the cache. Does anyone have any ideas on how to accomplish this or is it a futile attempt?

Thanks.

# Answer
> 4 votes
Yes you can by using an access callback which when defined calls a function. In this function you can analyze the path and based on that return TRUE or FALSE. When you return FALSE, the menu item is not visible. See the documentation of hook\_menu for more details.

A simple example:

```
// in hook_menu something like this, important part is the 'access callback'
 $items["menu/item"] = array(
     'title' => "menu item 1",
     'description' => 'Access test',
     'page callback' => 'node/1',
     'access callback' => 'check_path',
     'menu_name' => 'navigation',
     'type' => MENU_NORMAL_ITEM,
 );

// then define your access callback function
  function check_path(){
    // check path here and return TRUE or FALSE
    return TRUE;
  }

```

I just asked a similar question dealing with this: How to build a dynamic menu structure. You may find more information in that question that can help you.

# Answer
> 0 votes
Also worth mentioning there is the module path access. Here you can restrict paths by role, in a nice administrator interface. I have used this on several sites.

---
Tags: 7, routes
---


# Question
Title: How to get a friend's education and work history information using FBoauth module
Is there any way to get friend's education history and work history? I tried to send permission friend\_education\_histroy and friend\_work-history on fboauth.fboauth.inc file. But I got an error.

How will I pass the permission to Facebook and get my friend's info?

# Answer
> 1 votes
You may want to check your permissions to make sure that FB hasn't changed anything as they are notorious for changing their code. Here are the Permissions Reference.

# Answer
> 0 votes
you can simply check the required permission on the setting page "en/admin/config/people/fboauth" under user advance permission setting.

---
Tags: authentication-authorization, social-network
---


# Question
Title: EntityFieldQuery for getting the count of a user blog
EntityFieldQuery for getting the count of a user blog. Blog is a content type.

# Answer
Try this

```
global $user;

$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
 ->entityCondition('bundle', 'blog')
 ->propertyCondition('status', 1) // Getting published nodes only.
 ->propertyCondition('uid', $uid)
 ->count()
 ->execute();

print $count . ' blogs from ' . $user->name;

```
> 1 votes

---
Tags: 7, database
---


title: Exposing a form to anonymous users

text:
# Question
Title: Exposing a form to anonymous users
I'd like to provide a form where anyone can submit a new job opening. The goal is to allow anyone to submit a subset of fields for a jobs content type. Once submitted, the site admin would come in and fill in the rest and publish the new node. I've played with allowing anonymous access to create new nodes of the content type, but I just don't like the way the form looks and I don't want the user to see all the fields. Is there a way to hide some fields and set the published marker to unpublished for anonymous users and protect the form with a captcha or is creating a custom form the way to go?

# Answer
> 1 votes
I guess the Field Permission module is what you need. It allows you to set finegrained permissions to fields. Once installed you can set the permissions to edit, view etc to the field on the manage fields tab of your content type...

# Answer
> 1 votes
You can use "field permission" module to set field-level permission for any user roles. Field permission : http://drupal.org/project/field\_permissions

You can create a template file for your node edit form to modify it.

There is a captcha module in drupal which allow functionality to enable captcha for a form.

Captacha: http://drupal.org/project/captcha

---
Tags: forms
---


# Question
Title: Is there anyway to get more control over when CRON runs?
I've just setup some rules using the Rules Scheduler module. Everything is working as expected, except that when a rule is scheduled for 10:30am, it might not run til 11:00am, because that is when CRON runs.

Furthermore, when I go to the CRON settings page, it only allows me to select the intervals which CRON runs at.

Is there anyway to schedule a CRON task, e.g. everyday at 10:30? If is there anyway to be sure that if I set CRON to run at 1 hour intervals, CRON is running on the hour, and not some random time, based off when someone last pressed the run cron button?

I'm running Drupal 7 on a Windows platform is that makes a difference.

# Answer
You are using 'lazy' cron this means the cron process only kicks off if your cron requirements are met and someone visits the page

i.e. cron is set to run every two hours, cron hasn't been run for two hours and someone is on your site. (this could be 2 hours after the last cron run or 2 weeks)

It is only triggered by people visiting the site.

You need to setup a script to visit the site every say half hour. see this guide http://drupal.org/node/31506

Note: windows task scheduler is windows version of cron.
> 1 votes

# Answer
You can use "Elysia Cron" or "Cron Control" module to control the cron.

I have not worked on "cron control" module, but I have used "Elysia Cron" module to manage different cron in the site.

Elysia Cron: http://drupal.org/project/elysia\_cron Cron Control: http://drupal.org/project/cron\_control
> 4 votes

---
Tags: cron, rules
---


# Question
Title: Drupal Webforms arrange fields and labels
I need to create form like below

```
Label(Full Name)     TextField            Textfield

                 Label(First Name)    Label(Last Name)

```

How can I achieve this in webforms? In webforms there is no option to show labels below.

# Answer
> 2 votes
There is a module Arrange Fields which will help you.With this modle you can Drag and drop fields into any arrangement you want.

# Answer
> 0 votes
use field legend for(***Label(Full Name)***) and ***Label(First Name)*** this the name of field , to show form like this you can mange it from the css you can fiend some model like this http://drupal.org/project/formdefaults can help you to add more text

---
Tags: webforms
---


title: Drupal 7 Ajax Forms - select element

text:
# Question
Title: Drupal 7 Ajax Forms - select element
I've got a custom module form in Drupal 7. The code looks like this:

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

$form['tables'] = array(

        '#type' => 'select',
        '#options' => drupal_map_assoc(array("2012", "2013")),
        '#title' => t('Select year:'),

        '#ajax' => array(
            'callback' => 'form_example_dynamic_myajax',
            'wrapper' => 'abcd',
            'effect' => 'fade',
            'method' => 'replace',
            ),

       );

 return $form;
 }

 function form_example_dynamic_myajax($form, $form_state) {
     return $form_state['values']['tables'];
 }

```

So this simple code should update #abcd tag with the value of the 'tables' select. And the problem is that it works only for the first selection. If I chose 2013 it returns "2013" text in my #abcd tag. But, when I chose 2012, an #abcd tag stays unchanged. It still apperas 2013.

Here is the example: http://kuzaj.yamandi.com/pl/form\_example\_dynamic

Does anyone has any idea how to solve it?

# Answer
> 1 votes
The problem is that Drupal is unable to find the element #abcd in the further calls.

Since you are returning the values alone, it will replace the element #abcd with the value; so the element #abcd will be removed from the document, and it will not be available for further processing. That's why it is not updating the values in the second time.

To overcome this in `form_example_dynamic_myajax()`, you need to return the values like in the following code.

```
 function form_example_dynamic_myajax($form, $form_state) {
   return '<div id="abcd">' . $form_state['values']['tables'] . '</div>';
 }

```

---
Tags: forms, ajax
---


# Question
Title: How do I create a view from the user interface, and get the code to create it programmatically?
Is there a way to get the program code for creating a view from an existing view?

I first created a dummy view with the user interface. I would like to get the code that I have to insert in my module to create that view, so that my module replicates what I did with the UI. Is this possible?

# Answer
> 2 votes
That is a feature that the Views module already has. In Drupal 7, you need to follow these steps:

* In the page listing all the views defined in a site, select the "Export" operation
* In the next page, the Views module will show you the code that defines the view.

This is only the code that defines the views.

Another way, is the following one; in this case, you get the complete code to use to write a module.

* Enable the Bulk Export module that is listed under the modules that are part of the Chaos Tools Suite module
* On admin/structure/bulk-export, select the view(s) you want to export in a module, and enter the name of the module
* After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view

In Drupal 6, you need to follow these steps:

* Enable the View Exporter module that is part of the Views module (I am referring to version 6.x-3.0.)
* On admin/build/views/tools/export, select the view(s) you want to export in a module, and enter the name of the module
* After you click on the "Export" button, the next page will show you the content of the .info, the .module, and the .inc file you can use to write a module that implement the view

# Answer
> 0 votes
Yes, you can use feature module for the same. It will export the views into module and if you delete the views and enable the module, it will create views again.

Feature : http://drupal.org/project/features

You can find the tutorial of the feature in the drupal.org.

---
Tags: views
---


# Question
Title: How to call a function on node submit in drupal 7
I have created content type programmatically.. I don't want to display its node data in a block. Now I want to fetch data and save fetched data in a variable. How can I do it ?

Or else how can I call a function on node submit ?

here is my code :

```
function default_content_form_alter(&$form, &$form_state, $form_id) {
    debug($form_id);exit;

    switch($form_id) {
        case 'name_of_the_form':
            $form['#submit'][] = 'test_form_submit';
        break;
    }
}

```

# Answer
> 1 votes
```
function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  //echo $form_id; // get the form id
    switch($form_id)
    {
        case 'name_of_the_form':
           $form['#submit'][] = 'test_form_submit';
           break;
    }
}

function test_form_submit($form, &$form_state)
{
  drupal_set_message("How are you");
}

```

# Answer
> 0 votes
You have to hook in a custom module on hook\_node\_insert. I don't really understand the other parts of the request... :/

---
Tags: 7, nodes
---


# Question
Title: How to display only the menu items and not the parent menu?
I am trying to build on the footer a set of 3 menu links: About us, Terms of Use, Contact.

The problem is that I want to have only these 3 links as menus and I do not want their parent menu to be displayed. Can anyone help me on this?

When I do it, I can display the 3 links, but also their parent menu is shown. I want to display only the submenu items:

* MenuItem1
    + submenuitem1
    + submenuitem2
    + submenuitem3

Is that possible? Can The Panel module do this?

# Answer
The Menu block module is the way to go.

* Install the module
* Go to your blocks page
* Click on "Add new menu block"
* Select your menu and the level you want it to show
* Add that block to your footer region and you're set
> 1 votes

# Answer
You can use the Menu block module, or print sub-menus or any level menus.

```
echo theme('links__system_main_menu', array(
  'links' => menu_navigation_links('main-menu', '1'),
  'attributes' => array(
  'id' => 'main-menu-level-2-id',
  'class' => array('links')
)));

```
> 0 votes

# Answer
For three menu items, I wouldn't install another module. I'd create a new custom menu and add the items manually. The custom menu can then be set to be displayed in the footer by using the blocks admin page.
> 0 votes

---
Tags: entities, routes
---


title: How to add og:video tag at my site?

text:
# Question
Title: How to add og:video tag at my site?
I want to share my video site on Facebook.
Facebook detect only thumbnail of video.
I see France24.com add og:video on the source of site and show direct video on facebook.
I use auto\_opengraph but this module can't generate `og:video` How can i do?

# Answer
> 0 votes
new version of XML Sitemap module helped me.

> The XML sitemap module creates a sitemap that conforms to the sitemaps.org specification. This helps search engines to more intelligently crawl a website and keep their results up to date. The sitemap created by the module can be automatically submitted to Ask, Google, Bing (formerly Windows Live Search), and Yahoo! search engines. The module also comes with several submodules that can add sitemap links for content, menu items, taxonomy terms, and user profiles.

# Answer
> 0 votes
try this in your module

```
$tags =array();
//add stuff to tags
 foreach($tags['og'] as $key => $value)
                 {
                  $meta = array(
                    '#tag' => 'meta',
                    '#attributes' => array(
                      'property' => 'og:' . $key,
                      'content' => $value
                    )
                  );
                  drupal_add_html_head($meta, 'og_meta' . $key);
                 }

```

---
Tags: 6, meta-tags
---


# Question
Title: How to add custom functionality on per-date base to nodes that use date fields for an event ticket system?
For an event ticket system I have created a node type with multiple date fields including start- and end-dates.

```
-EVENT1-
Date A
Date B - Date F
Date G

- Event2 -
Date B
Date C
Date E - Date G

```

Now I need to add a boolean field to every date that is inserted into an event node to possible mark it as 'sold out event day'. How is this possible when I want to use the start-/end-date option? I don't want to create a nodetype 'date' and then reference its nodes to an event-node... Thnx!

# Answer
In the database (the appropriate table for your date field), you have a column called 'delta' wihch start from 0

In your example Date A (delta = 0) Date B - Date F (delta = 1) Date G (delta = 2)

Your probably can add an hidden (for non-admin user) field in your node type (for example an textfield serialized array) to store the boolean value for each delta. This can be done programmaticly with rule an php algorithm on each node\_save. In view you can also get the delta value
> 1 votes

---
Tags: 7, datetime, entities
---


# Question
Title: Admin Approval for Webform Submitted data
I am new to drupal , and need functionality like , When any Users submit Webform then i am displaying that submitted data in another page . but in between i need Admin Approval so for that how to change code in Webform module.

I have used all modules like MODR8 , RULES , VBO , Moderation etc.

if anyone knows plz help me becoz i am trying to solve this problem from last 2 weeks.

Thanks in advance.

# Answer
> 0 votes
i have solved my problem by creating new table in database and create new custom module at adminside.

i have stored webform submitted data in 1 table and in my custom module at adminside display that data and add 1 field in table like published with checkbox , so when admin tick checkbox and click on submit button , in my table i have updated status to 1.

Thanks, Megi

# Answer
> 0 votes
You can try something like this for admin approval: 1. create custom content type; 2. create fields just like your webform has; 3. copy copy webform-confirmation.tpl.php and change the name webform-confirmation-NID.tpl.php 4. there write something like this:

```
include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1);
$sid = $_GET['sid'];

$submission = webform_get_submission($nid, $sid);

$otzyv_text = $submission->data[1]['value'][0];
$name = $submission->data[2]['value'][0];
$email = $submission->data[3]['value'][0];
$title = mb_substr($otzyv_text, 0, 10);

$node = new stdClass();
$node->type = 'response';
$node->title = $title;
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = $otzyv_text;
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'filtered_html';
$node->field_name[$node->language][0]['value'] = $name;
$node->field_e_mail[$node->language][0]['value'] = $email;
$node->uid = 1;
$node->status = 0;
$node->promote = 0;

node_object_prepare($node);
node_save($node);

```

(this is what i've done when my customer wanted to have an ability admin approval). By this way you will have unpublished nodes when someone submits your form (administrator can publish them whenever he wants). After that in IF statement you can write something like:

```
$node = menu_get_object();
if($node->type == 'YOUR TYPE' && $node->status == 1) {
  // Display submitted data... You can fetch them from node object
}

```

or with Views module you can create block or anything you want by that content type...

---
Tags: 7
---


# Question
Title: Using taxonomy term value as title for the view
I created a taxonomy, called `Galleries` for images on the web site:

1. Our Rooms
2. Our Food and wines
3. Our Services

Then I created a gallery for each of the terms, using views. I wanted to override the title of gallery to the term value, as it is shown in this subform for Contextual filters:

But the id of term is used in the url:

http://hotelcentralpark.ro/gallery/1

http://hotelcentralpark.ro/gallery/2

etc

So, instead of words: "Our Rooms", "Our Food and wines" I get "1" and "2", if I check the box "Override title".

How can I show the value of the term instead of it's id? But keep id in the url.

# Answer
Create the function, using hook\_views\_pre\_render

```
function custom_views_pre_render($view) {
      if ($view->name == 'gallery') {
            // get the $tid from the view's args
            $term = taxonomy_term_load( $view->args[0] );
            if( $term ){
                  $view->build_info['title'] = $term->name;
            }
      }
}

```

Mind, that in Drupal 7 drupal\_set\_title doesn't work for views:

https://stackoverflow.com/questions/8343623/drupal-7-drupal-set-title-not-working-in-views
> 0 votes

# Answer
Try to use the hook\_views\_pre\_render on your view to override the page title

```
function custom_views_pre_render($view) {
  if ($view->name == 'your_view_name') {
    // get the $tid from the view's args
    $term = taxonomy_get_term( $view->args[0] );
    if( $term ){
      drupal_set_title( $term->name );
    }
  }
}

```
> 1 votes

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


# Question
Title: How to programmatically create new user with custom fields?
I want to create user with some custom fields. I have created extra fields through config \> people \> site information \> manage fields and fields like first name, last name, city etc. I want to create user with this custom fields.

**How can I create user programmatically?**

# Answer
> 25 votes
Using `user_save` Drupal function you can create new users like so:

```
$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'john.doe@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
  //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);

```

---
Tags: 7, users
---


title: Should Features modules be unit tested?

text:
# Question
Title: Should Features modules be unit tested?
When you write a module, you write unit tests (or you should - I don't because I am a bad person, but I want to change - honest).

Should modules generated with Features be unit tested where applicable/possible, or is a suite of Selenium tests enough?

For example, say I have a Feature that has a node type and a couple of user roles and/or permissions for said content type. Is it good practice (or even necessary) for SimpleTests to be written to test creation of my content type?

For clarity, I am aware of Unit test for custom content type, but I am after an answer regarding all unit testable functionality, not just content types.

# Answer
The Features module has its own tests that verify that the operations done on a feature (e.g. adding or reverting it) as successful. Drupal already has tests to verify that for example, users with the right permission can read/write/update a node, or that a Drupal variable is effectively saved. The Views module should have its own tests to verify that exporting/importing a views is done correctly.

Apart from those tests, you should not have any reason to write tests for the Feature module, as the existing tests should already covers any possibility. The only case I would write a test for a feature is when the feature is using custom code you wrote.
> 1 votes

---
Tags: features, testing
---


title: Remove link from $title in comments

text:
# Question
Title: Remove link from $title in comments
I'm using Drupal 7. When I post a comment to an article, its title looks like `<a class="permalink" rel="bookmark" href="/comment/9#comment-9">comment title</a>`.

I need only the “comment title” to be displayed, **without the link**.

I found the code in the comment.tpl.php template where the title of the comment is printing.

```
  <?php print render($title_prefix); ?>
  <h2<?php print $title_attributes; >><b><?php print $title></b></h2>

  <?php print render($title_suffix); ?>

```

As is said in the file description, `$title` already contains the link, so I can’t change it!

> `$title`: Linked title

Does anybody know if there is a way to print the comment's title without a link?

# Answer
> 7 votes
Instead of

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

```

You can do:

```
<?php print check_plain($comment->subject); ?>

```

# Answer
> 6 votes
Easiest way is to paste this code in template.php of your current theme, replace the word `THEMENAME` with the name of your theme (lowercase of course) and flush your cache:

```
/**
 * Preprocess theme_comment()
 */
function THEMENAME_preprocess_comment(&$variables) {
  // Remove all HTML tags from the title
  $variables['title'] = strip_tags($variables['title']);
}

```

---
Tags: 7, comments
---


# Question
Title: How to make search on all fields (title and tags as well as body)?
The built in search engine in Drupal 7 doesn't search on the title or tags fields, just on the **body** of the node. I need to be able to search on all fields.

What is the best module to install for this if I'm running Drupal on Apache on Windows?

# Answer
> 32 votes
One thing you can do to control which fields are included in your search index is to go to your specific content type's '**Manage Display**' page.

So go to Structure --\> Content types --\> Your content type --\> Manage display.

On that screen, you'll see a collapsed section called 'Custom Display Settings'. Just click on it to expand it. You should see that you can check to enable the 'Search index' display to be customized (Usually only the teaser or summary is included for customization by default). Check the 'Search index' box and save:

That will provide you with a brand new "Search index" tab on this screen. Click on it and start customizing which fields you want to be included for this content type's search index:

---
Tags: 7, search
---


title: Rebuild imagecache

text:
# Question
Title: Rebuild imagecache
I have an imagefield per node that's run through imagecache. Since imagecache caches on-demand, cache files/variations aren't created until they're first requested. So if I update a bunch of images, re-deploy, or otherwise blow the whole cache, it's up to first visitor to process that file.

**How can I spare that user the load time and manually rebuild the whole cache?**

The last time this came up, I programmatically loaded every node link with jquery ...

Seems like a perfect Drush plugin ... should probably look into writing it, but I'm curious if anyone else has a solution for this.

# Answer
> 12 votes
You could create a custom module and then use hook\_cron() to rebuild the imagecage.

## Update

I've just spent the last hour trying to work out how to do it server-side and I think I've cracked it.

```
/**
 * Implements hook_cron().
 */
function rebuildimagecache_cron() {
    global $base_url;

    // get published nodes
    $result = db_query('SELECT nid FROM {node} WHERE status = 1');
    while ($nodes = db_fetch_array($result)) {
        $node = node_load($nodes['nid']);
        $node_type = $node->type;

        // get cck fields for the current nodes node_type
        $fields = content_fields(NULL, $node_type);
        foreach ($fields as $key => $value) {

            // only deal with file fields that use the image widegt tyoe
            if ($value['type'] == 'filefield' && $value['widget']['type'] == 'imagefield_widget') {
                $preset_tokens = explode('_', $value['display_settings']['full']['format']);
                $imagecache_preset = $preset_tokens[0];
                $field_name = $value['field_name'];

                // iterate over each field instance
                foreach ($node->$field_name as $field_instance) {
                    $filepath = $field_instance['filepath'];
                    $cachedpath = imagecache_create_path($imagecache_preset, $filepath);
                    file_get_contents($base_url . base_path() . $cachedpath);
                }
            }
        }
    }
}

```

How it works:

1. Get all the published nodes
2. For each node gets the node type
3. Gets an array of fields for the current node being iterated
4. Iterates over all the fields and checks if any are image fields
5. If image field found then get image cache preset associated
6. Iterate over image field instances of node
7. For each image field instance get image filepath
8. Convert image file path into image cache path
9. Read file path using file\_get\_contents() over HTTP to force image cache to generate cached image.

I've tested it and it worked great for me in Drupal 6. A Drupal 7 version would be slightly more tricky due to the changes in the underlying File API.

You'll have to create a custom module and paste this function in. Make sure you also change the hook name from `rebuildimagecache` to the name of your custom module.

I've used `hook_cron()` so that it will run when cron is ran but you could run it manually via a `drush` command.

# Answer
> 5 votes
Low tech approach...

1. Create a new node view.
2. Set a filter for the content type thatcontains the image fields.
3. Add your image fields, using whatever ImageCache preset you want to pre-cache.
4. Set it to not page, with no node count limit.
5. Load the view.
6. Watch your server crush under the load. If timeout, reload the view.

Oh, and make sure only admins have permissions on that view.

# Answer
> 4 votes
One performance tip: You don't need to load the whole image contents to trigger imagecache, you can also just request the headers. So this line:

```
file_get_contents($base_url . base_path() . $cachedpath);

```

becomes

```
get_headers($base_url . base_path() . $cachedpath);

```

# Answer
> 3 votes
My solution:

```
function example_cron() {
    $result = db_query('SELECT fid, uri FROM {file_managed} WHERE filemime like :mime AND status = :status', array('mime' => 'image/%', 'status' => FILE_STATUS_PERMANENT));
    $queue = DrupalQueue::get('generate_image_styles');
    foreach ($result as $img_info) {
        foreach(image_styles() as $style) {
            $derivative_uri = image_style_path($style['name'], $img_info->uri);
            if (file_exists($derivative_uri)) continue; // skip existing files
            $data = (object) array(
                    'style' => $style,
                    'img_info' => $img_info,
                    'derivative_uri' => $derivative_uri
                     );
        $queue->createItem($data);
        }
    }
}

function example_cron_queue_info(){
    $queues['generate_image_styles'] = array(
        'worker callback' => '_example_generate_image_styles',
        'time' => 30
        );
return $queues;
}

function _example_generate_image_styles($data){
    if (!file_exists($data->derivative_uri)) {
        image_style_create_derivative($data->style, $data->img_info->uri, $data->derivative_uri);
    }
}

```

# Answer
> 2 votes
There was an attempt to get this kind of thing working, see Imagecache Batch but I'm not sure where the development of these features stand. You don't mention if you're dealing with D6 or D7 but I would look into the actions and rules stuff in 6.x-2.x-dev and see where it's at.

# Answer
> 0 votes
This was done and works well, see here https://drupal.org/node/587086

Try the full file patch at the end of the thread. Make sure you run it inside `/sites/all/modules/imagecache/imagecache.drush.inc` and not at root, as is standard.

---
Tags: 7, media
---


title: Node relations (one content type)

text:
# Question
Title: Node relations (one content type)
Question: I have a content type "VIDEOS" and have added 20 videos - 1 through 20. I want to achieve a functionality like if you are watching video x, the next 3 videos are showing in the sidebar, example -\> when you are watching video 2 in a block in the sidebar videos 3, 4, 5 are showing up. When you watch video 7 - in the sidebar videos 8, 9 10 are showing up and so on. Any ideas? I know it will be done somehow with Views but cannot figure it out.

BR, Ivan Ivanov

# Answer
> 5 votes
I would do that with a little code in a custom module...

For the purposes of this example my module is called misc, but replace everywhere is says misc with the name of your your module.

First create a block:

```
function misc_block_info() {
    $blocks['next_four'] = array(
        'info' => t('Show the next 4'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );
    return $blocks;
}

```

And then define where it's content comes from:

```
function misc_block_view($delta = '') {
    switch ($delta) {
        case 'next_four':
            $block['subject'] = '';
            $block['content'] = next_four();
            break;

    }
    return $block;
}

```

And then define the content of the block:

```
function next_four() {
    $output = '';
    if(arg(0)=='node') {
        $node = node_load(arg(1));
        $query = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('n.type', $node->type)
            ->condition('n.status', 1)
            ->condition('n.nid', $node->nid, '>')
            ->range(0, 4)
            ->orderBy('n.nid', 'ASC');
        $nids = $query->execute()->fetchCol();
        $nodes = node_load_multiple($nids);

        $output .= '<ul>';
        foreach($nodes as $node) {
            $output .= '<li><a href="'.drupal_get_path_alias('node/'.$node->nid).'">'.$node->title.'</a></li>';
        }
        $output .= '</ul>';
    }
    return $output;
}

```

What this code does is:

1. Take the nid of the current node
2. Does a query to get more nodes of the same type with an nid height than the current page.
3. Loads each node and outputs the node title, with a link to the node.

This will work for any content type. If your HTML is going to be any more complex than this then I would suggest using the hook\_theme function to create a template file for your block.

---
Tags: nodes, views
---


# Question
Title: custom form module not showing upload functionality
```
<?php

function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('form_test_form'),
     'access callback' => TRUE,
    );
   return $items;
}

function form_test_form($form,&$form_submit) {
   $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
    $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

```

Hello all,

Can anyone explain to me why this will not work? I am trying to test the form submission and I created a module folder with a .info file. I am using mywebiste/formtest, but every time I try and load the page it says "page not found." I have been looking at tutorials and they all seem to work fine but it seems that I must be doing something wrong. Any thoughts?

Any and all help is greatly appreciated, thank you in advance.

# Answer
Try to clear all cache of your Drupal website and try to access your url: http://wwww.your\_domain.com/formtest
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Decide which modules to enable / disable in make file
I have a make file in which modules are downloaded, but how do I decide which ones are enabled?

# Answer
Drush make only downloads projects; if you want to enable some modules, you must do that with an installation profile. An installation profile contains a make file, plus some code to configure your site.

If you're using Drupal 7 and would like to create a starting installation profile from an existing site, see http://drupal.org/node/1368242. There is a patch there that will create a profile for a D7 site. The issue is marked "needs work" because the code templates for D6 are not in place yet.
> 2 votes

---
Tags: users, drush
---


# Question
Title: How can I show video and images in slideshow with lightbox style?
I need to combine pictures and videos to come out in one Slideshow and when they click on an image or video is displayed in a lightbox. (I have only a 1 video)

Currently, video I have them separately and displayed on a lightbox as follows:

```
<a href="[field_video]" rel="lightvideo"><img src="[field_thumbnail]" alt="image_thumbnail" /></a> <!-- Where [field_video] is the URL of the video -->

```

And if possible, show a small text in Slideshow with the image/video. As a caption that says if a video or image.

Using Drupal 7.

# Answer
I achieved this some months ago... you can see an example in here http://www.entretierras.com/en on the left sidebar there is a block (slideshow) called "Our routes in pictures"

What we did:

First of all - New content type: \- Create a new content type. In my case I called it "slideshow sidebar" \- Add image field \- Add video field (see http://drupal.org/project/video\_embed\_field) \- The idea is the content can have an image or a video, but not both. (I control this by using Conditional fields module) Optional \- Create some nodes

* Create an image style

Second - Create a view: \- Create a view. Block presentation. Showing content fields. \- Install Colorbox and Views slidehow modules. Colorbox is used for opening the slide in a lightbox way. Views slideshow is needed to create the slideshow. \- Add the fields you have created above. \- Apply a filter for the "slideshow banner" content type \- Select the format as slideshow and configure it as your requirements \- On every field (in the view) select the formatting as color box and aply the image styles you have created previously.

Hope this could help.
> 1 votes

---
Tags: 7, media, files, javascript, views
---


# Question
Title: How do I create different user registration pages?
In my project, I need to have two types of user: normal user (who can buy products) and merchant user (who can upload products).

I made the registration page by creating the user\_register.tpl.php template file. I don't have any idea about how to make another registration page which will be used for merchant users.

Is there a contributed module available for this?

# Answer
Basically you have to create only one registration page. And you have to create two roles. **Normal User and Merchant User** Add these roles field on user registration page using Auto Assign Role module. Configure permissions for the respective role. Like Normal users can **buy product** and Merchant users can **create product** If you are using Commerce Kickstart then you will have permission for adding product and other permissions.
> 0 votes

# Answer
Have you looked at Ubercart Marketplace? It's especially effective for what you're describing, especially if you're not shipping physical products.
> 0 votes

---
Tags: users
---


# Question
Title: How can I render a birthday field to display only Day and month
I am trying to render a birthday field to display only Day and month.

user's birthday is 07/21/1971

When I print:

```
<?php print render($user_profile['field_birthday']);

```

I get this: Wednesday, July 21, 1971

I added this to get only day and month:

```
<?php print date("F jS", mktime(0,0,0,$account->profile_birthday["month"],$account->profile_birthday["day"])); ?><br>

```

it gives me this: November 30th

Any idea why? Thanks for any help, RJ

# Answer
Go to **/admin/config/regional/date-time/formats** and select Add format. You will be prompted to enter a format string. This is a php date() formatting string. If you enter "F j" (without the quotes" the date format will be the full month name and the date eg April 11. Refer to the manual for a full list of options.

Then go to **/admin/config/regional/date-time** and select Add date type. Call your new type 'Birthday' and select the date format you just created from the select list.

Under **/admin/config/people/accounts/display** select your field and configure the display to use the 'Birthday' format.
> 2 votes

# Answer
You can install the Date module and configure a new display format in its configuration page as `F jS`. Then in your profile display mode settings use that format for the date field.
> 1 votes

# Answer
This isn't really a Drupal question, but a PHP question:

```
print date("F jS", strtotime($user_profile['field_birthday']));

```

Make sure your system's date format is the same as your Drupal's date format though or you could end up getting mixed up months/days! (american date format vs european)
> 0 votes

---
Tags: users
---


title: Drupal image style issues

text:
# Question
Title: Drupal image style issues
I have a peculiar problem. I have 3 sites on a Debian/Nginx setup. Let's call them site1.com, site2.com and site3.com. After upgrading to 7.20, site2.com and site3.com image styles stops being created while site1.com is working. I installed fresh Drupal 7.22 in a subdirectory in site1.com and site2.com (also upgraded all the sites to 7.22). The fresh installations won't create image styles either. I thought the fresh installation in site1.com subdirectory will work since site1.com itself works fine but that's not the case. I'm totally lost here. The Nginx site conf settings are the same for all the sites so I'm not sure it's a server issue. I have spent the past few days reading about this but can't an issue similar to mine.

I just followed the instruction here http://drupal.org/node/244924 to fix any file permission issues but the image styles are still not generated. I also tried this module http://drupal.org/project/image\_allow\_insecure\_derivatives, it didn't work either.

# Answer
It was my sever setup after all. Thanks to this post: Is there a common nginx conf for Drupal 7 sites?, I was able to fix the issue. Image styles now work on all my sites.

My initial setup was

```
    location ~ ^/sites/.*/files/styles/ {
            try_files $uri @rewrite;
    }

```

The above setup worked for a while and was working for one of my sites but won't work after upgrade for the others for some reason.

I changed it to this

```
    # Image styles for D7
    location ~* /sites/.*/files/styles/ {
            access_log off;
            expires 30d;
            try_files $uri @rewrite;
    }

```

and it's working now.
> 5 votes

---
Tags: 7, media
---


# Question
Title: Losing superfish menu item after logging out from administration panel
I have a superfish menu as my nav menu bar. I customised it and added some pages for each menu item.

When I log out of the administration panel, as a general user I can only see the first menu item, all other menu items are gone.

\[edit below\]

Right, found out that the problem was because my other three menu items are all link to '.../add/node'. Superfish will not show empty links on the menu bar. However, I actually don't want some of the items link to anywhere as they all have submenu items. I want the link to remain empty so that the user can click on the submenu item. How can I achieve this?

# Answer
When an item in a menu tree is unavailable because of a lack of permissions, the entire tree below that item will disappear.

You should probably restructure your menu to use placeholders. Have a look at the Special menu items module.
> 2 votes

---
Tags: routes, navigation
---


# Question
Title: How to list similar products using views in Commerce Kickstart?
I am trying to list other products in the same category using the Views module when browsing a product.

For example, I am browsing drinks/drupal-commerce-wake-you; I want to list all other products in the "drinks" category, to build similar, or related products.

How can I achieve this?

# Answer
> 7 votes
Try this

1. Create view (block)
2. Add fields (title, a small image, date, whatever you like). Or teasers, what works as well.
3. “Arguments” is from now on called “Contextual filters”, so go there.
4. Add the filters: “Content: Has taxonomy term ID *(with depth)” and “Content: Has taxonomy term ID depth modifier”*
5. Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box “Load default filter from node page, that’s good for related taxonomy blocks.” → now check the boxes of the taxonomies you want involved here
6. Now you need to add the second filter in order to exclude the current node from the list. Click \[+\] button of the contextual filters section.
7. Select Content: Nid
8. Set the ‘when argument is not present’ to ‘Provide default argument’
9. Set the ‘Default argument type’ to ‘Content ID from URL’
10. Go to “MORE” , and check the “Exclude” box.
11. *Move the filter “Content: Nid” to the top position.*
12. Add a block to your view and embed the block on your node pages
13. Save your view

# Answer
> 0 votes
Another easy solution is creating a taxonomy of categories or whatever variation types you want to filter; add the taxonomy to your product fields.
Create a view adding the *Has Taxonomy Term*, selecting the taxonomy you added.

---
Tags: views, commerce
---


title: Pull all articles as JSON

text:
# Question
Title: Pull all articles as JSON
I am trying to pull all articles from my site in form of JSON.

I know it can be done by either Services, RESTful Web Services or Views Datasource but I don't know how to do it. I am a complete n00b in Drupal.

Could you specify me, with an example hopefully, that how can I pull all articles in a JSON and show that JSON through a URL?

# Answer
Judging by its description Views Datasource might be the way to go, but it seems to be still not ready for production. There is no even beta version as far as I can tell. But your task can be easily achieved by creating your own custom module.

Create your own module (you can read more about this process here).

And in your module do the following:

```
//Your implementation of hook_menu, create url endpoints here
function YOURMODULENAME_menu() {
    $items = array();
    $items['path/where/i/want/your/json/to/be'] = array(
        'title' => t('list of articles'), // can actually be arbitrary text here
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'access callback' => TRUE,
    );
    return $items;
}

//Page callback function that renders the json endpoint
function your_function_name() {
    $query = "SELECT * FROM {node} n WHERE n.type = :type";
    $result = db_query($query, array(':type' => 'article'));
    $json_data = array();
    foreach ($result as $record) {
        $node = node_load($record->nid);
        $json_data[] = array('nid' => $node->nid, 'title' => $node->title, 'body' -> $node->body['und'][0]['value']);
    }
    print drupal_json_encode($json_data);
    exit;
}

```

I didn't test this code and you might have more fields in article datatype, but I think you should get the idea how this can be done. Just query the database for the list of nodes of specific type, compose an array of data and output json.
> 1 votes

# Answer
Thanks Alex, Thanks Sibiraj,

I was able to do it through Services + REST.

I created a view named content and configured it to show all the Published Articles.

This is what generated for me:-

```
http://myurl.com/views/content.json

```

Could I ask one more question, that how can I control how many articles could be shown. I am implementing Dynamic scrolling in my app and I want to show 10 Articles at a time. When a user scrolls till the bottom end, I want to show next 10 articles.

The problem with this URL is that it shows all the articles. Could I say append a variable with it, let's say through which it can control the start and end of article index?

```
http://myurl.com/views/content.json?/start_article=0&end_article=10

```

Many Thanks.
> 1 votes

# Answer
You can try some module like feeds or services or views\_data\_export or node\_export
> 0 votes

---
Tags: 7
---


# Question
Title: Reference (include) php file in content summary
In my content summary section I will have the same information for each node. I would like to reference an external php file so that down the road if I ever need to change the summary content I don't have to go through each one and manually change it.

I set text format to php code.

In the summary I added:

```
<?php include("external.php"); ?>

```

Problem is that I am not seeing the contents of the php file. In fact, I am not seeing any sign of it in my code.

Am I going about this the wrong way?

Edit: I basically want to be able to change some static HTML that needs to belong in the summary field of my nodes if I ever need to without having to go into each node and change it manually. The text will be the same for all my nodes.

# Answer
If you have a custom module for your site, put the file in that module directory, add it to the mymodule.info file,

```
file[] = external.inc

```

and put the include statement in the mymodule.module file. Use the model here if you are unfamiliar.

Make the code a function, named for instance `mymodule_standard_summary()`, and then use:

```
<?php
print mymodule_standard_summary();
?>

```

in the summary of your nodes. This should get you started.

EDIT:

Rather than trying to embed your code in the page like this:

```
<?php
  // Embedded code
  print $result;
?>

```

instead you should set it up in a function in your file like this:

```
function mymodule_standard_summary() {
  // Your code
  return $result;
}

```

I hope this makes it a little clearer.
> 1 votes

---
Tags: 7
---


# Question
Title: D7 - db_select: order by most recent, commented status
I'm writing my custom module. I use the modules Statuses and 'fbss\_comments' (part of the Statuses module). Comments are used to comment on statuses.

Using the following code I get a list of results:

```
 $query = db_select("statuses", "thread")->distinct();
        $query->join("fbss_comments", "comment", "comment.sid = thread.sid");
        $query->fields("thread", array("sid", "sender", "created", "message"));
        $query->fields("comment", array("created"));
        $query->orderBy("comment.created", "DESC");
        $result = $query->execute();

```

Now the list of results will be sorted by the most recent posted status. I want to achieve the following: **sort the result list by statuses with the most recent comments**

Some clarification: normally status(100) will be shown above status(30). When I comment on status(30), status(30) should be shown above status(100). On top of this, when I create a new status(101), this status should be shown on top of the result list.

I hope my goal is clear to you, sadly, I have no idea how to achieve this.

Any advice or help is much appreciated

**edit:** I've managed to order the results by the most recent commented statuses, however, if a status has 9 comments, the status is shown 9 times. Any advice why/how this happens?

**edit 2:** I probably should use -\>distinct(), I've added it after the db select statement, but this doesn't work (probably because I select two tables)

# Answer
> 3 votes
You have a classical case, that requires using '`HAVING`' `SQL` operator. Suppose, we have 2 related tables:

```
| table1 |
|--------|
|   id   |
|--------|
|    1   |
|    2   |
|--------|

```

table2.f\_id is the FK for table1.id

```
|         table2        |
|--------+------+-------|
|     id | f_id | order |
|--------+------+-------|
|      1 |    1 |     1 |
|      2 |    1 |     2 |
|      3 |    2 |     3 |
|      4 |    2 |     4 |
|--------+------+-------|

```

And you want to get all the records from table1 with MAX of the related table2.order. And sort them by table2.order. You must use this SQL to get the data:

```
SELECT
  table1.id AS id1,
  table2.id AS id2,
  table2.order
FROM
    table1
INNER JOIN
    table2
ON
    table1.id=table2.f_id
GROUP BY
    table1.id
HAVING
    MAX(table2.order)
ORDER BY
    table2.order DESC

```

And you will get:

```
| id | id1 | order |
|----+-----+-------|
|  2 |   3 |     3 |
|  1 |   1 |     1 |
|----+-----+-------|

```

Fiddle

Converting this SQL to Drupal, we'll get this:

```
$query = db_select("table1");
$query->innerJoin("table2", NULL, "table1.id=table2.f_id");
$query->addField("table1", "id", "id1");
$query->addField("table2", "id", "id2");
$query->addField("table2", "order", "order_field");

$query->groupBy("table1.id");
$query->having("MAX(table2.order)");
$query->orderBy("table2.order", "DESC");
$result = $query->execute();
while($row = $result->fetchAssoc())
{
      var_dump($row);
}

```

So, for your case, this query must work:

```
$query = db_select("statuses", "thread");
$query->innerJoin("fbss_comments", "comment", "comment.sid = thread.sid");
$query->fields("thread", array("sid", "sender", "created", "message"));
$query->fields("comment", array("created"));

$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();

```

---
Tags: 7, database
---


title: how many taxonomies i should use?

text:
# Question
Title: how many taxonomies i should use?
there are different content types and associated with different taxonomies. for example forum content type associated forum taxonomy, article content type is associated with tag taxonomy and gallery content type is associated with gallery taxonomy. i want to show related contents in front page blog, but taxonomies different. how can i associate them? with using only one taxonomy for all content types or else?

# Answer
> 1 votes
Forum and Gallery taxonomies are used to maintain the information structure of their respective content types. They should not be mixed.

A tagging taxonomy, on the other hand, is generally freestyle, and allows a user to give keywords describing the content. There is no reason to restrict it to a single content type. Why not use your tags on all content types.

# Answer
> 0 votes
Taxonomy fields, like any field, may be attached to multiple content types. It sounds like the view you're displaying on your home page needs to draw from one taxonomy. Therefore, your options are to use one taxonomy across all of the content types, or to build a different view with a better way to implement your concept of "related content."

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


# Question
Title: How to NOT share content between multi sites?
Try as I might cannot stop all changes in one sub site copying to other. They have two separate databases and settings files and conf files but because of necessary symlink to share core code base , everything else is being shared right along with it.

How can I stop this sharing everything between subsites when drupal core is in first subsite and symlinked to second?

Why is it even happening when have two sep db set up and two sep settings.php?

I don't want changes to be made to subsite2 when I make changes to subsite1 and vice versa as is happening now.

mysite.com (static html) in /var/www/html

sub1.mysite.com (drupal install) pointing to mysite.com/sub1

/var/www/html/sub1/sites/sub2

sub2.mysite.com (symlink to sub1 in html folder) pointing to mysite.com/sub2(symlink vs)

No necessity to add sites.php or even change httpd or conf file with symlink.

My theory is you must have drupal core files in html folder not a subdir linked to subdomain below it. I will test tomorrow.

No I think I need to just know what to put as base url in conf file? Do I direct it to html/mysub.site.com or to html/sub1/sites/mysub.site.com ?

# Answer
I run several multi-sites and nothing is being shared between them except core and the modules and themes below `sites/all/`. If *more* than this is shared (your question specifies "everything"), then you've not set up your multi-site right.

I've written a tutorial about setting up a multi-site here. I hope the instructions are clear enough to follow.

Setting up a multi-site where the primary site is in a sub-directory is not different from setting up any other multi-site, provided your `DocumentRoot` points to the right place.

From your latest comment, I finally understand that you're trying to do the same thing as the person at http://drupal.org/node/1882182.

In that case, you need to understand that this person is *not* using the *subdirectory* method. He is using the *subdomain* method. You can't mix these methods, you must use one or the other.

And if you're using the *subdomain* method, you must *not* use a symbolic link (as you indicate in your question that you're using). Instead, you must configure DNS and your vhost to point to the directory that is your `DocumentRoot` for Drupal (in your case, it sounds as this should be `/var/www/html/sub1/`. This will take care of the fact that your Drupal core is installed in a sub-directory with a plain HTML-site in the web-root. You must also create the following sub-directory in the Drupal `sites` directory: `sub2.mysite.com`. Copy the `default.settings.php` into `sub2.mysite.com`. Then make `sub2.mysite.com` your working directory and immediately copy `default.settings.php` to `settings.php`. Make sure that both are writeable by the web server user. The `sub2.mysite.com` subdirectory will hold your `settings.php`for `sub2.mysite.com`. Then go to your ISPs control panel and configure DNS for `sub2.mysite.com` to resolve to your main site's IP-adress. Finally create the following ServerAlias: `ServerAlias sub2.mysite.com` in your main site's vhost configuration file.

You should now be able to point your web-browser to `http://sub2.mysite.com/` and be greeted with default Drupal installaton screen. You can then proceed and install the multi-site instance you've created. If you get anything *else* than the default Drupal installaton screen at this point, something has gone wrong and you need to find out what this is.

(All this assumes you're using Apache2 as your web-server. If you're using something else, you need to figure out the equivalent of `DoccumentRoot` and `ServerAlias` on your brand of web-server.)
> 6 votes

# Answer
Read Multisite

> If you are running more than one Drupal site, you can simplify management and upgrading of your sites by using the multi-site feature. Multi-site allows you to share a single Drupal installation (including core code, contributed modules, and themes) among several sites.

**Overview of the Process**

1. Create a new database for the site (if there is already an existing database you can also use this by defining a prefix in the installation procedure).

A new database shall not have your other sites content in it, unless you add them.
> 1 votes

---
Tags: multi-sites
---


# Question
Title: Changed Comment Module and database table - how to revert changes?
Yesterday, I posted this thread which was subsequently locked for being too localized. I think this is much more searchable (and I still need help!) but I'm sorry for the bad thread.

Like mentioned in that thread, I changed different files in the comments module folder and added columns to the database table. This sort of disabled comments, both the settings in page content settings and their appearance on the page normally.

I tried to fix this by: uploading a completely new 'comments' folder (I have a back up if that was a bad idea) from a new copy of the core, and deleted those table fields. Still no sign of fixing any of the problems I created.

How do I return the comments to their normal setting so I can approach the altering I was planning on doing the right way this time?

# Answer
> 2 votes
First: **Do not hack core!**

To restore your site to a stable state, revert to the default theme, back-up your database and the `sites/` sub-directory and anything below it. Then download a fresh copy of the core and install it. Finally, restore the `sites/` sub-directory, your database, and the theme.

Having extra tables in the database that Drupal does not know about does not do any harm, but you may drop those tables that you created yourself before backing up the database.

---
Tags: 7, comments
---