# Question
Title: How do I create an entity using the properties of another entity?
I am currently working on a custom "quiz" like module in Drupal 7. The way it works is as follows: a site administrator creates a bunch of reading assignments, and associated questions that go with those readings (the reading might be a downloadable PDF, or a link to some online content). I currently have an entity called "reading" which has a title, description, media type field (pdf or link), and a group of question text fields, where the admin can create an arbitrary number of questions. Thus, a constructed reading entity might look like this:

```
========= READING ENTITY ===========
Title:       Some Great Paper
Description: This great paper was written by Joe Schmo, and it is great.
Media Type:  PDF
File Field:  /path/to/the/uploaded/file.pdf
Questions:
             What did Joe mean by 'Persistence is necessary?'
             How would you apply these ideas to your life?

```

Now, I am trying to create the "Assignment" entity. This is an entity that an instructor would create by picking a reading from the pool of reading entities an administrator has created. The assigned reading entity would look very similar to the reading entity, however it would have some additional fields. For example, it would need an indicator that the student has submitted the answers, and a grade field for the instructor. It would also need fields for instructor notes, and student answers. Since there needs to be an attached answer and notes field for each of the questions, I also created an "AssignmentQA" entity.

Finally, there is a requirement that if an instructor creates an assignment, and later on an administrator updates the "Reading" entity (Say, changes questions, or the pdf file to be downloaded, etc..) that this change is NOT seen in already created assignments. Thus, everything would need to be cloned. I see the Assignment and AssignmentQA entities associated with the above reading as looking like this:

```
============== ASSIGNMENT ENTITY ===============
Title:       Some Great Paper    <--- cloned from the Reading entity
Description: This great paper... <--- cloned from the Reading entity
Media Type:  PDF                 <--- cloned from the reading entity
File Field:  /path/to...         <--- cloned from the reading entity
Instructor:  User reference to the instructor
Student:     User reference to the student
Status:      [Assigned, Completed, or Graded]
Notes:       General notes from the instructor to the student...
QAs:
             reference field to QA1
             reference field to QA2

============== ASSIGNMENTQA ENTITIES ==============
ID:          QA1
Question:    What did Joe mean by 'Persistence is necessary?' <--- Copied from Reading's Q1
Answer:      The student's answer to this question.
Notes:       Instructor's notes on this particular answer

ID:          QA2
Question:    How would you apply these ideas to your life? <--- Copied from Reading's Q2
Answer:      The student's answer to this question.
Notes:       Instructor's notes on this particular answer.

```

Of course those IDs for the AssignmentQA entities are pseudo-code used for clarity.

So with all that being said..

1. Does this sound like a reasonable approach?
2. Is there a better way to think about this/do this?
3. If it is reasonable, is there a way to pass a reading entity to the Assignment Entity so that I can properly construct an assignment from the reading data?
4. And, how do I go about cloning the pdf file field, such that the pdf file can't be deleted from the server if it is updated, but the old version has already been assigned to someone? (e.g.- I'd like to use the updated PDF for any new assignments created, but keep the old one around for old assignments).

# Answer
> Does this sound like a reasonable approach?

You've put some thought into this, it doesn't sound unreasonable -- nor does it sound simple.

> Is there a better way to think about this/do this?

If your reading Questions are simply textareas great, if they're radio boxes and select widgets look into leveraging an existing "quiz" or form builder like: webform, webform\_entity or the quiz module.

> If it is reasonable, is there a way to pass a reading entity to the Assignment Entity so that I can properly construct an assignment from the reading data?

I have cloned nodes before in Drupal 6/7, which isn't too hard. I think you need to really iron out a workflow for "if I make a reading -- I can create Assignment(s) and/or AssignmentQA entities". You could try creating this workflow logic for instructors using workflow, maestro or using a set of Rules.

If you try and just "I made a reading entity". You could always make a view that allows you to create a hook\_menu() link to a new node edit form using a Reading Node as a menu argument -- then you could see the original node's fields easily for cloning.

> And, how do I go about cloning the pdf file field, such that the pdf file can't be deleted from the server if it is updated, but the old version has already been assigned to someone? (e.g.- I'd like to use the updated PDF for any new assignments created, but keep the old one around for old assignments).

In D7 the file\_managed FAPI element allows you to set an "owner" module for the FID, I believe only that module may deem the file as 'deleted'. So using a custom FAPI override you could specify a module you control as the enforcer for this ruling. The D7 file\_entity module is seeking to add views to track individual file usage of FIDs i'm not sure if it's ready for prime time usage.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: how many content type fields can I have on a drupal site?
I have a Drupal site for tracking equipment. I have a bunch of content types that are basically questionnaire forms that are related to the equipment. I need to associate those with specific equipment nodes.

ex. equipment node "1500" has 6 forms that each have numerous fields that need to show up under it when you view the full node. I've done this with entity views attach and it works fine. But one of these forms has about 85 fields in it. Most of these fields are checkboxes/radio buttons. Some of the other forms have 40-50 fields.

I recently noticed my site's performance slowing to a crawl after adding these fields to one of the content types and I'm worried that there are too many fields. I can't find any info on how many fields I can use though. Does Drupal limit the number of fields? Or is there some other limitation that could cause a problem?

RJ

BTW: I was going to use webform, but I can't access the fields in views with that (don't think so, anyway)

# Answer
> 2 votes
In Views, take a look at the SQL that it is generating in the preview of the view. If you see tons and tons of JOINs, one for each field, that is most probably the cause of the slowdown. What Drupal does is create a table for each field that is shared between content types and that means Views has to join everything back together again based upon the nid. So, if this is happening, you might be able to improve performance by having each of these fields unique to an individual content type. In that case, just as long as they are single value fields, they will just be another column in the database table defining the content type and can be grabbed all at once.

---
Tags: entities
---


# Question
Title: How to display only parent terms of hierarchical terms  in Views field
In the Views UI I set up the `Relationship "Taxonomy:Parent term"` and then a `Field "Taxonomy: Term"` with that relationship.
But the problem is that It displays the parent terms of all the vocabularies (I have several vocabularies). I also tried the `Field "Taxnomy:All terms"` as it can limit the terms by vocabularies but it can't have the `Relationship "Taxonomy:Parent term"`

Is there any way to display only the parent terms of one certain vocabulary for hierarchical taxonomy in a view field?

# Answer
I think my answer to a similar question would be useful:

> I believe that your problem would be solved by adding a relationship to your view. Here are the steps:
>
> 1. Add Relationship: taxonomy terms on node
> 2. Select the vocabulary you want to use.
> 3. Add Relationship: parent term
>
> Now you should be able to add fields from any of the terms or their parents, and to use them as contextual filters as well.

Note that this is for Drupal 7
> 3 votes

# Answer
have you tried filters? As far as drupal 6 is concerned, filters by taxonomy term can let you choose from which vocab you only want to show. With drupal 7 it would be the same. I'm not on my dev server right now but you can check filters.
> 1 votes

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


# Question
Title: Escaping special characters in custom submit handler redirect URL?
My submit handler contains a redirect to a URL formatted thus:

```
mysite.com/node/123/edit?step=step_2

```

and my problem is that it's appearing in the browser bar as:

```
mysite.com/node/123/edit%3Fstep%3Dstep=step_2

```

which messes up my redirect.

How do I escape the characters "=" and "?" for use in a URL for redirection from a custom submit handler?

# Answer
> 3 votes
If you use an array as the value for `$form_state['redirect']`, it will eventually be passed to `url()`. So you can use the same options as for that function to build up a structured query string:

```
$path = 'node/' . $nid . '/edit';
$query = array('step' => 'step_2');
$form_state['redirect'] = array($path, array('query' => $query));

```

There's more explanation in the documentation for the `drupal_redirect_form()` function.

---
Tags: redirection, forms
---


title: Keep modules enabled/installed?

text:
# Question
Title: Keep modules enabled/installed?
I used node\_export and UUID to export and then import content from one Drupal 6 site to another.

Do I need to keep these modules enabled for any reason after the import?

# Answer
On Drupal 6, as per your question, you most likely do NOT need to keep node\_export around after your content import/export is done. It doesn't create any database tables and will only remove config settings variables when you uninstall.

As for UUID it is (depending on your settings) probably a good idea to keep it around. It adds/alters some db tables adding its UUID to your content, etc. It would probably be less trouble to keep it rather than remove it and it shouldn't have an impact on the performance of your site.
> 0 votes

---
Tags: 6
---


# Question
Title: Remove blog-like recent content from <front> page
Is there a straightforward way to remove the default content, ie recent posts list, from the front page?

I've read about creating my own page and assigning certain blocks to that page and then setting it as the default starting page.. but I've already got my homepage mostly set up and wondered if it would be easy to do it the other way so I don't have to change all my other settings.

# Answer
As long as your blocks have been configured to show up on `<front>`, it doesn't matter what your front page is: you can swap it out to whatever you want and it won't affect anything except what appears in the main content area.

So, to swap the default recent posts list with a page of your own (whatever that page may be):

1. Go to *Configuration**System**Site information* (i.e. head over to `http://example.com/admin/config/system/site-information`)
2. In the *Front page* fieldset, change *Default front page* from "node" to whatever path you want to use, instead.

To make sure your blocks show up on the front page instead of (or in addition to) specific pages:

1. Click *configure* next to the block you want to modify.
2. Under the *Visibility settings* tab group, select the *Pages* tab, change *Show block on specific pages* to "Only the listed pages" and add `<front>` to the text area on its own line.

Now, now matter what you set the *Default front page* to, the block will show up on the front page.
> 4 votes

# Answer
Another way is to add the following code in your **HOOK\_preprocess\_page()** function in **template.php**:

```
if (drupal_is_front_page()) {
  if (isset($variables['page']['content']['system_main'])) {
    unset($variables['page']['content']['system_main']);
  }
}

```

This causes the default Drupal frontpage node-list in your theme to disappear. This method won't modify your front page title.

You'll probably want configure *(admin/config/system/site-information)* the **Number of posts on front page** option to lowest possible value (i.e. 1) to save some performance too.
> 7 votes

# Answer
What content do you want to have on the front page? Why dont you try Panels http://drupal.org/project/panels You can use a panel and make it your homepage. You will also keep your block settings. Also what version of drupal are you using?
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Get selected value from Dropdown list of views
I have a drop down list of different views for the users to select on a content type page in Drupal 7. I need to get the value of selected view from the drop down and display it in the form of selected view.

```
$value = $_GET['select id'];
$view = views_get_view('value');
print $view->preview('default');

```

I am not sure from where I should get the ID of the drop down field.

# Answer
> 1 votes
Not sure I fully understand the issue it would help if you asked a direct question. Here are some thoughts though.

To get a list of applicalbe view checkout this funciton form the node reference module:

```
function references_get_views_options($entity_type) {
  // Filter views that contain a 'references' display. This actually returns a
  // list of displays (the same view appears several times).
  $displays = views_get_applicable_views('references display');

  // Filter views that list the entity type we want, and group the separate
  // displays by view.
  $entity_info = entity_get_info($entity_type);
  $options = array();
  foreach ($displays as $data) {
    list($view, $display_id) = $data;
    if ($view->base_table == $entity_info['base table']) {
      $options[$view->name . ':' . $display_id] = $view->name .' - ' . $view->display[$display_id]->display_title;
    }
  }

  return $options;
}

```

The key function here is the "views\_get\_applicable\_views(&display\_type)". The rest of the function just filters the list for an entity type (node, taxonomy term, comment, or user are the common defaults). Then formats the data as an options list.

You can embed this list in a form as so (I wrote this code to do a similar task to what it sounds like you are doing:

```
$views_options = references_get_views_options('node');
if ($views_options) {
  $views_options = array('' => '<' . t('none') . '>') + $views_options;
  $element['view_and_display'] = array(
    '#type' => 'select',
    '#title' => t('View used to select the nodes'),
    '#options' => $views_options,
    '#default_value' => $default_view,
    '#description' => 'description',
  );

```

In the submit handler you save the view option. Something like:

```
$view = $form_state['values']['views_and_display'];

```

Then in the view hook of the content type you run an embed.

```
$view_info = explode(':', $display['settings']['view_and_display']);
$result[0]['#markup'] = views_embed_view($view_info[0], $view_info[1], $args);

```

Hope that helps. I wrote a module that did something similar for a client not too long ago so this is all working code form that module. It actually registers a display handler to output a node reference field as a view so it would give me a list with exactly the correct fields desired.

---
Tags: navigation, views
---


title: Change Time Format

text:
# Question
Title: Change Time Format
I'm confused about all of the time formats and then each format seems to have a matching format with a `pm` attached at the end. Does the `pm` signify that it will use 12 hour am and 12 hour pm vs 24 hour time? Pic attached:

# Answer
> 1 votes
You happened to look at the example time formats at the wrong time of day. If it was an hour later, say 1:04 pm you would have seen

* 26.08.2012 - 13:04
* 08/26/2012 - 1:04pm (highlighted)

By the way you can also define your own formats to be used with the "Long", "Medium" and "Short" date types, if you don't like the pre-canned options. Look for the "Formats" tab under the date time settings:

`admin/config/regional/date-time` in Drupal 7 (the screen shot is D7.x)

Further, you can also define new date types (e.g. I often create "Time of day" or "Year") that you can then assign a particular format (ideally one that only shows hh:mm:ss AM/PM -`h:i:s A`\- or year - `Y` \- to match your naming convention). It is a bit confusing, but it is a two step process, but it is very flexible. Creating a "Year" only date type is great for using with the Views module to make display groupings on year.

---
Tags: 7, datetime
---


# Question
Title: How to pass an argument from the URL to a views exposed filter?
I have a view with an exposed filter as a select list.How can I pass to the exposed filter an argument from the URL?The argument is the Taxonomy ID (tid).I want the exposed filter to show every time the same Taxonomy Id as the Tid that exists on the URL.Is this possible? Thanks

# Answer
> 2 votes
Assuming you are using arguments (contextual filters D7.x) you can make another display that is attached to the main display. This attached displays should be programmed to provide a summary list when the argument is not present, and to present the list as a jump menu. You can then set up the jump menu to select the current URL argument (contextual filter). This provides a select menu for an argument, that shows the current argument if it is specified in the URL. An example of this is the results summary page I created for our club's main fundraising race.

The main view page display has three url arguments: year, race category, and gender. The attached view has year as its first argument and race category as the second argument. The second argument is programmed to list available categories (for that year since year is a required argument) if no category URL argument has been specified. When setting up the jump menu settings it was set to "select the current argument". The attached display is also set *not* to inherit the parent display's arguments. That way when we link (main event page) to a specific category results, the selector shows the results filtering taking place and allows people to easily select a different summary.

**Note** \- this was done in D6.x using Views 2.16

**Clarification** \- it is critical that the attached jump menu display is set **not** to *inherit* the parent display's arguments, but that the jump menu is set to *display* that argument. Otherwise the attached view won't display the jump list when the url argument is present, rather it will display the resulting content (however you set that up). For my results summary page I had to pass the year argument to the attached jump selector view via PHP - eke!!

---
Tags: views
---


# Question
Title: What's the difference between "Contexts" in CTools/Panels and in Context module?
I've been wondering this for a while and always assumed they were different things, but the fact that the Context module uses CTools for its Plugin API kinda confuses me even more...

Can someone please break it down for me please? Thanks!

# Answer
This is essentially a duplicate of Panels or Context module?. However, Lullabot has a pretty good breakdown on the differences, and at the end of the day, it comes down to a matter of preference (I personally tend to go with Context).
> 2 votes

# Answer
Main difference is panels context (ctool context under the hood) its for interacting in a panel's environment while Context module interact with whole Drupal site.
> 1 votes

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


# Question
Title: Redirect to a custom page after a node has been added or edited
Using `hook_form_alter`, how can I redirect a user to a a custom page after creating or editing a node instead of the node that was created or edited?

The current code for `hook_form_alter()` is the following one:

```
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'custom-node-form') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
  }
}

```

# Answer
> 17 votes
```
function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
    $form['#submit'][] = 'custom_node_submit';
  }
}

function custom_node_submit($form, &$form_state) {
  $form_state['redirect'] = 'choose/your/path';
}

```

The code redirects the form independently from the button clicked to submit the form. If you want to redirect a form only when a specific submission button is clicked, then you should used the following code.

```
function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
  }
}

function custom_node_submit($form, &$form_state) {
  $form_state['redirect'] = 'choose/your/path';
}

```
* The form ID doesn't contain hyphens. The form ID is the name of the PHP function that generates the form (a.k.a. the form builder), and a PHP function cannot contain hyphens in its name.
* The form ID is passed to the implementations of hook\_form\_alter(), hook\_form\_BASE\_FORM\_ID\_alter(), and hook\_form\_FORM\_ID\_alter(). `hook_form_FORM_ID_alter()` doesn't really need it, as it is called for a specific form, while the other two hooks are invoked for more than one form.
* The first function is the implementation of hook\_form\_BASE\_FORM\_ID\_alter(); in this case, the base form ID is "node\_form" that is the base form for the node edit form.
* The node edit form contains `$form['#node']`, which is the node object for the object being edited; "custom" is the short ID for the content type you want to redirect the users once they edit a node.
* Altering `$form_state['redirect']` from `hook_form_alter()` doesn't have any effect; it needs to be set from a submission handler.

# Answer
> 9 votes
This code works on a Drupal 7 site.

```
/**
 * Implements hook_form_alter()
 */

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['actions']['submit']['#submit'][] = 'mysubmit_node_submit';
  }
}

function mysubmit_node_submit($form, &$form_state) {
  $form_state['redirect'] = '/homepage';
}

```

# Answer
> 4 votes
This can be done by setting `$form_state['redirect']`, for example using one of the following lines.

```
$form_state['redirect'] = "some-internal-path";

```

```
$form_state['redirect'] = array($path, $options_array, $http_code);

```

It's the same arguments you would pass to `drupal_goto()`.

# Answer
> 2 votes
Not sure if this is an option for you, but if this is a content type you could achieve this pretty quickly by using the Rules module by setting a rule to be triggered on update or creation of a certain content type.

---
Tags: 7, forms, redirection
---


# Question
Title: How to use Views & Entity Reference to create dynamic URLs that are based title from the referenced node
Here's my situation:

I have two content types: Procedure, and Testimonial. Testimonial has an entity reference field where you can point to one or more procedures.

My goal is to create a view of testimonials with a dynamic URL like 'example.com/testimonials/procedure1', where procedure1 is the title of the node that is referenced from the testimonial. So, the idea is that this page would exclusively show testimonials that reference the procedure1 node.

So, I created the view. I added a relationship "Entity Reference: Referenced Entity". I then created a contextual filter that uses this relationship.

At this point, if I do not use a relationship in the contextual filter, I can get this working by using the following pattern: example.com/testimonials/7, where 7 is procedure1's node ID. But, I'd like to use the title in the URL- not the node ID.

Does anyone know where to go from here? Am I going about this the wrong way?

Thank you!

# Answer
This is how I solved a similar problem: Create a filter on the title and use the relationship: entity. Then, in a custom module put something similar to:

```
    function MYMODULE_views_pre_view(&$view, &$display_id, &$args){
      switch($view->name) {
        case 'view_name':
          $value = arg(x);
          $view->display['default']->handler->options['filters'['field_name']['value'] = $value;
        break;
      }
    }

```

I'll probably go ahead and build a more universal module out of this because of how often I use it. The benefit is you can inject an argument as a filter. I use dashes for spaces and include a str\_replace(); to replace dashes with spaces for the filter. You loose some validation, etc. but there's a bunch of modules that provide filters but no contextual relationship. This binds the two in a hacky way.
> 1 votes

# Answer
Try one of these modules:

They will allow you to create looking good alias 'estimonials/PROCEDURE\_NAME' for pages as 'testimonials/PROCEDURE\_ID'.
> 0 votes

# Answer
What about Automatic Nodetitles? http://drupal.org/project/auto\_nodetitle/

Base the title on the referenced entity and then the path on the title of the Testimonial, which will be automatically set.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How can I save an Advanced Action on Drupal 7 installation when there's no save button?
I am at the 'edit / configure an advanced action page' and I try to create or edit one of my "send email" actions (admin/config/system/actions/configure/...) However, I notice that the form has no save button. It's not there whether overlay is on or off. How do I save it? My core and modules are all up to date as of today. I am logged in as adminstrator and have rights to do everything (I checked that).

Here's my setup: Drupal core 7.15 Includes: Aggregator, Block, Blog, Book, Color, Comment, Contact, Contextual links, Dashboard, Database logging, Field, Field SQL storage, Field UI, File, Filter, Forum, Help, Image, List, Menu, Node, Number, Options, Overlay, PHP filter, Path, RDF, Search, Seven, Shortcut, System, Taxonomy, Text, Toolbar, Tracker, Trigger, Update manager, User

Modules

Backup and Migrate 7.x-2.4 Chaos tool suite (ctools) 7.x-1.2 Content Access 7.x-1.2-beta1 Entity API 7.x-1.0-rc3 Features 7.x-1.0 Feeds 7.x-2.0-alpha5 Job Scheduler 7.x-2.0-alpha3 Mailhandler 7.x-2.5 Pathauto 7.x-1.2 Rules 7.x-2.2 Strongarm 7.x-2.0 Token 7.x-1.2 Token Filter 7.x-1.1 Webform 7.x-3.18 Release notes

Includes: Webform

Themes The Morning After 7.x-1.0-beta3.

# Answer
> 0 votes
The Module "Token 7.x-1.2" is the culprit. By disabling this module, the Save button again appears on the page. Of course, to disable the Token module, I must also disable two other modules first. Hence it's not a fix at all but a work-around because I have to re-enable this module for PathAuto. I will attempt to submit an issue with the Token module.

---
Tags: actions
---


title: Taxonomy bulk edit in Drupal 7

text:
# Question
Title: Taxonomy bulk edit in Drupal 7
I have been trying to find a good, working method to do some bulk taxonomy operations in Drupal 7.

The Administration Views module doesn't appear to work - I just get page not found errors when trying to access any of the views.

So, I have been trying to follow this guide here: http://learnbythedrop.com/drop/166 . However, this is for Drupal 6 and I can't find the corresponding options in Drupal 7. There is no Style option in the view dialog, and Format contains:
Grid HTML list Jump menu Quicktabs Table Unformatted list, But nothing for VBO.

Can someone help here? This is where drupal really falls down IMO - total lack of up to date documentation and lots of time spent trying to find modules to do simple things which should be in core.

# Answer
> 3 votes
I don't believe there is a really easy way to do this with d7 yet. Views bulk operations will probably be your best bet for the future, as there is work going on to provide this functionality (see: http://drupal.org/node/1142062).

In the meantime, vbo does work with the rules module, so it looks like it might be possible to use rules and vbo together to accomplish bulk taxonomy updates, although I don't think this is trivial. This screencast: http://vimeo.com/26884701 and this comment: http://drupal.org/node/1057158#comment-4792118 might help to get you started.

# Answer
> 1 votes
VBO now has a Modify Field Value option which you need to enable through Views. The options are in the Bulk Operations FIELD. Although at the moment there's an issue where updating taxonomy term fields for multiple nodes at the same time results in duplicate taxonomy terms with different TIDs added to your vocabulary.

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


# Question
Title: How to create menu link to an individual field within a node in Drupal 7
Assume a content type with two user fields, being a description and a file. Assume that a few content items, or nodes, have been created that are based on this content type.

Description Image Joe Brown www.images.com/picture\_of\_JoeBrown Joanna White www.images.com/picture\_of\_JoannaWhite Jeremy Green www.images.com/picture\_of\_JeremyGreen etc

Easy enough to create a menu item that points at the node. Once the user has opened the node they can click on the image's URL and retrieve the image.

Easy enough to create an "external link" that points directly at the image and jumps straight to it. However the external link's address is static.

How does one create a menu item the jumps *directly* to the image that is currently stored in the Drupal node/content **without** an intermediate step?

In this example, I need to append the name of the field that contains the image url to the menu node address so that the system will show the person's current image with a single click from the menu without an intervening node/content display.

This seems like it should be easy, but I can't see it......

# Answer
The quickest might be with a MENU\_LOCAL\_TASK in a custom module, e.g.:

```
function YOURMODULE_menu() {

  $items=array();

  $items['node/%node/avatar'] = array (
    'title' => 'Avatar',
    'page callback' => 'YOURMODULE_node_avatar',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'weight' => 64,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;

}

function YOURMODULE_node_avatar($node) {
  // drupal_goto($node->field_avatar[0]['filepath']); // Drupal 6
  drupal_goto($node->field_avatar[LANGUAGE_NONE][0]['filepath']); // Drupal 7 (I think :)
}

```

which would create an `Avatar` tab for you that when clicked on would display the image in field\_avatar. Obviously you'd have to change that up to your exact field (and I think I got the D7 language stuff right in there if you are on D7).

It could also be called directly, e.g. `www.YOURHOST.com/node/1/avatar` would display the avatar of node with nid 1. If this is going to be how you access it, you could change `MENU_LOCAL_TASK` to `MENU_CALLBACK` and then the `Avatar` tab wouldn't show up on the page.
> 1 votes

---
Tags: routes
---


# Question
Title: How do I programmatically change the workflow status?
It appears that, although Drupal 6 had `workflow_transition()`, that function is not available in Drupal 7.

Is there an equivalent function? If not, what else should I use?

# Answer
`workflow_transition()` is a function implemented from the Workflow module, and it still is implemented in the Drupal 7 version of the module.

Drupal 6 code that used `workflow_transition()` would work in Drupal 7
without changing how that function is called.
> 1 votes

---
Tags: 7, workflows
---


# Question
Title: Remove duplicate data in revision tables in database
> **Possible Duplicate:**
> How to disable the revision feature completely?

How can I disable duplicate data in database. one example is this image:

# Answer
You can't unfortunately.

The concept of storing field data and revision data in two different tables is hard coded into entities at the very lowest level.

If you want to change this behaviour you're looking at a major rewrite of the entity and field systems, and I very much doubt there's any way to do it without hacking a fair few of the core files.

The best thing to do is just accept that this is how Drupal stores its data and try to work with it rather than try to get around it.
> 2 votes

---
Tags: database, nodes
---


# Question
Title: How to show hide other content fields when we select radio buttons?
I have created 2 radio buttons. When i select 1 radio button, then represented field has to display and hide other field represented to next radio button. When I select radio1, only textfield1 has to display and radio2, only textfield2 has to display.

# Answer
This could also be done by using states that are available in Drupal core. For example you could set that an element in a form should only be visible if another element has the value "x".

```
    $form['my_element']['#states'] = array(
      'visible' => array(
        ':input[name="some_other_element"]' => array('value' => 'some_value_that_has_to_be_set'),
      ),
    );

```

More examples at form\_example\_states\_form.

You can add states to elements in an implementation of hook\_form\_alter or add it directly to the form if you are programming it yourself.
> 6 votes

# Answer
Use the Conditional fields module:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
> 2 votes

---
Tags: entities, nodes
---


title: Multi site cron set up

text:
# Question
Title: Multi site cron set up
I am doing some updates on existing drupal multi site set up and am unable to set up cron for subsites. Subsites are accessed in a different way (example.com/site1 example.com/site2 ) From browser accessing example.com/site1/cron.php runs the cron but its not running from crontab.

```
45 11 * * * /usr/bin/lynx -source http://example.com/site1/cron.php
45 11 * * * /usr/bin/wget -O - -q -t 1 http://example.com/site1/cron.php
45 11 * * * curl --silent --compressed http://example.com/site1/cron.php

```

Tried all these but its not triggering cron functions.

# Answer
> 0 votes
It was not resolving the host names. Added an entry to `/etc/hosts` and it worked fine.

---
Tags: 6, multi-sites, cron
---


# Question
Title: Is it possible to inherit a cck into another CCK and assign multiple values to it
I have been searching stackoverflow, drupal forums, drupal.stackexchange for how to create **multiple values** for a **group**. I came across several posts regarding the issue mainly Drupal Custom CCK field with multiple child fields and cck multiple groups but I din't find (may be) the exact solution. I even tried **Groups module** but din't understand how to organize fields.

Is it possible to inherit a cck and call that cck into another cck and assign multiple values to it I know that node reference field type will do this but can i assign multiple values ? To be brief:

Now I want to call Asset cck in Events and assign multiple values to it just like eventname- Launching a new iphone

* assetname(title of the pdf)-- iphone 5 introduction **Text field**
pdf(link) -- www.mysite/flder/iphone5intro.pdf **File type**
* assetname(title of the pdf)-- iphone 5 user manual **Text field** pdf(link) -- www.mysite/flder/iphone5manual.pdf **File type** etc

It can have multiple values and it should also support **views**

help, and please ignore for any mistakes made, I will be very thankful for any alterations made.

# Answer
From the first look at this, it seems you are wanting to create a cck content type with a multiple value filefield field so you can upload multiple pdfs per node.

If that is the case, make sure you have the FileField module installed if D6 (it's in core in D7) and then you can, after creating the content type, add a field, select it's type to be File, and then in configure, allow it to have 1,2,...10 or any number of values.

After that, everything "just works," including Views.
> 1 votes

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


# Question
Title: Add variations to coupons commerce module of drupal
On my commerce site, I want to add a coupon which can be use for a particular brand or catagory (taxonomy : product attributes).I am using commerce module with drupal 7. Any one help me on rule making...

# Answer
> 0 votes
Sure, no problem. Just create a new rule that triggers on the event "Calculating the sell price of a product."

You want the condition: Entity has field, then choose the commerce\_product. This is the product reference field that is inherent in line items. Then, choose the condition: Entity has field again. Choose the brand entity reference field that you have built into your product type. Basically, you will be reaching through the line item, through the product the line item refers to, to hit the brand that product is tagged with. Next, choose the condition: Data comparison. For Data to Compare, choose that brand reference field. For Data value, switch from data selection to direct input mode, then choose the brand you wish to target.

Finally, under actions, add one of the commerce line item actions based on the mathematical operation you wish to do with that brand price.

This should do it!

---
Tags: commerce
---


# Question
Title: Where can I add this jquery code to apply to a view block?
I have some jquery that I need to apply to a view that's being displayed as a block. The only template we're using for this particular view is views-view-grouping--my-view.tpl.php. I've tried adding the jquery to the beginning of this file, but as expected (because it runs recursively for each group) it's being added to the rendered source before every rendered group, instead of just once.

Where is the best place for me to add jquery code so that it's only added to the rendered source once? It's just two lines of code aside from the document.ready declaration, so I'd rather not have to put it in a separate file and call it conditionally from various page templates.

# Answer
One quick way could be to add it inline in a preprocess function.

```
    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
      }
    }

```

If you prefer you could also add it as a file that you store in your theme. This would include a file called myfile.js under the folder for your theme /js

```
    /**
     * Implements template_preprocess_views_view().
     */
    function THEMENAME_preprocess_views_view(&$vars) {
      $view = $vars['view'];
      // Add Javascript when the view with the name news is shown and the display id is your-display-id.
      if ($view->name == 'news' && $view->current_display == 'your-display-id') {
         global $theme_path;
         drupal_add_js($theme_path . '/js/myfile.js');
      }
    }

```
> 3 votes

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


# Question
Title: node translations and too many menu items
I use Drupal 7, locale and the i18n modules. I've setup a mini site with node translation.

I have the following `EN` nodes:

* `node/1` About
* `node/2` Terms
* `node/3` FAQ
* `node/4` Contact

and the following `FR` nodes:

* `node/5` A propos \[translation of `node/1`\]
* `node/6` Contacter \[translation of `node/4`\]

The main site is the English one and the French menu will always be equal or a subset of the English one (same structure).

I've implemented the site using 2 menus, one for `EN` (4 links + Home) and one for `FR` (2 links + Home). This works but doesn't scale well if I have many (500) nodes per language and:

* I decide to add a new language
* I decide to reorder some nodes around (change parents etc)

I've also implemented the site using 1 menu (the "Main Menu") and it contains all links (4 links + 2 links + Home). This works but still has the previous disadvantages and in addition:

* links are mixed when the user is selecting parent menus

So, my question is, assuming I need a 1-to-1 mapping from `EN` to `FR`, or a subset of `EN` but with the exact same structure, isn't there a simpler way to solve this? Ideally I'd want to have a single Menu which would specify something like:

* /about -\> node/1, /fr/about -\> node/5
* /terms -\> node/2
* /faq -\> node/3
* /contact -\> node/2, /fr/contact -\> node/6

Is this possible?

# Answer
> 0 votes
No it's not possible because each menu link can point to a specific (one) node. When using node translation the different translations of a node are other nodes.

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


# Question
Title: Recreating vocabulary and term pages by using views
Let's say I have a vocabulary named "Gallery" and terms inside of it: "One", "Two" and "Three".

Every term have a image field.

What I would like to accomplish:

After going to mysite.com/gallery I would like to have a custom view with grid of images of all terms from specific vocabulary. After clicking an image I would like to be redirected to mysite.com/gallery/\[term-name\] where I would have another view that would show a grid of specific fields from nodes related to this term.

I think it has something to do with contextual filters? But I'm not sure if it is possible to relate two views that way (so one would have path "/gallery" and other "/gallery/%" and one would dynamically create paths for the other), is it? :/

How would you approach a problem? Even if views wouldn't be valid solution.

PS. The main problem I'm struggling with now is to create a links in one view (/gallery) to other view (/gallery/%) :/ .

Regards!

# Answer
> 0 votes
try to create a views Taxonomy terms, add fields in this order: **Taxonomy term: Term ID (Term ID)** (enable Exclude from display, Thousands marker None), **Taxonomy term: Name** (uncheck "Link this field to its taxonomy term page" option, open "SHOW REWRITE RESULTS" fieldset, enable **Output this field as a link**, in **Link path** enter gallery/\[tid\]), this is solution for your PS.

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


# Question
Title: maintenance mode after error occurs while running update
Error occurs While I'm running update for my drupal site. And it stuck in maintenance mode. I can't log in to it using /user/login.

I changed $update\_free\_access = TRUE in settings.php and run update.php. And I see this screen.

It says ctools module is missing. How can I re-install module when I can't login as administrator?

**\[Edit\]** In the hope of getting the module back, I restored the database with my backup sql-dump via phpmyadmin. After that, it came to 500 internal server error.

I don't know what was wrong? Is there any way I can restore my site back on?

Thanks in advanced!

# Answer
Most housekeeping tasks like these can be done using Drush, a Drupal command line managing tool. For example, you can reinstall the module using

```
drush pm-disable modulename
drush pm-uninstall modulename
drush pm-enable modulename

```

the database can be updated by issuing

```
drush updatedb

```

And code is easily updated with

```
drush pm-update

```

To use drush you need a shell access to a server your site runs on. No authorization as Drupal user is needed.
> 1 votes

---
Tags: maintenance-mode, updating
---


# Question
Title: override theme function in facetapi module
I am trying to change the markup of links created by the facetapi module. The theme function is here

```
function theme_facetapi_link_inactive($variables) {
  $accessible_vars = array(
    'text' => $variables['text'],
    'active' => FALSE,
  );
  $accessible_markup = theme('facetapi_accessible_markup', $accessible_vars);
  $sanitize = empty($variables['options']['html']);
  $variables['text'] = ($sanitize) ? check_plain($variables['text']) : $variables['text'];
  if (isset($variables['count'])) {
    $variables['text'] .= ' ' . theme('facetapi_count', $variables);
  }
  $variables['text'] .= $accessible_markup;
  $variables['options']['html'] = TRUE;
  return theme_link($variables);
}

```

I am trying to override this function so I can change the markup without editing the module files. I've tried MYTHEME\_preprocess\_facetapi\_link\_inactive and using a custom module but both times I can print the variables and they are correct but the links are still displayed wrong.

```
function MYTHEME_preprocess_facetapi_link_inactive($variables) {
  $accessible_vars = array(
    'text' => $variables['text'],
    'active' => FALSE,
  );
  $accessible_markup = theme('facetapi_accessible_markup', $accessible_vars);
  $sanitize = empty($variables['options']['html']);
  $variables['text'] = ($sanitize) ? check_plain($variables['text']) : $variables['text'];
  if (isset($variables['count'])) {
    $variables['text'] .= ' <strong>' . theme('facetapi_count', $variables) . '!!!</strong>';
  }
  $variables['text'] .= $accessible_markup;
  $variables['options']['html'] = TRUE;
  return theme_link($variables);
}

```

Am I going about this the wrong way?

# Answer
> 1 votes
You're nearly there, but a preprocess function doesn't look applicable to what you're trying to do. A preprocess function is used to set up variables for a theme function, not to actually produce the markup.

What it looks like you're trying to do is to override `theme_facetapi_link_inactive()` completely, in which case you don't use a preprocess function, but instead you call the function `MYTHEME_theme_function_name()` and the theme engine will use that instead of the original function.

So all you need to is change the name of your function like so:

```
function MYTHEME_facetapi_link_inactive($variables) {
  // Same code as in your example
}

```

After you clear the caches Drupal will start using that function in place of `theme_facetapi_link_inactive()` whenever it's called.

---
Tags: search, theming
---


# Question
Title: How can I display custom user information on a page that is not a profile page?
I'm looking to display User information on an individual page, pulling custom fields to display the information.

For example, if a visitor of the site come across a user page, it would display:

* Name (not username)
* Pictures that they've uploaded
* An about me paragraph

Maybe a few other custom fields in the future, but the main part is that I need to know how to call these from Drupal.

I'm new to Drupal, but I've worked with Wordpress and Joomla a lot in the past and I'm looking to move onto Drupal, so please, be patronising when you explain!

# Answer
> 0 votes
It really depends on how you want to achieve this. Using Panels and Views (as suggested by Dmitry Vyal) you can easily build this without writing a single line of code.

No matter which solution to use, you will need to understand entities (users are entities) and fields (data attached to entities). Both are basic concepts you will find everywhere in Drupal.

If you want to do it in code, you should create a custom module and understand Drupal hooks system. In this nodule, you can declare a page available at a specific by implementing the `hook_menu()` hook. Since you want to display information from a user on this page, you will need to include `%user` in your page's path. Combine this with the `'page arguments'` property of your menu item to receive the user object as argument of your page handler function (ie/ the `'page callback'` property of the menu item).

# Answer
> 0 votes
Probably you should create a panel with two views. One for a general user information and other for stuff like uploaded pictures.

Hope these tutorials will allow you to get started

http://nodeone.se/sv/node/20

http://mustardseedmedia.com/podcast/episode32

---
Tags: hooks, users
---


title: Hook_schema and multiple databases

text:
# Question
Title: Hook_schema and multiple databases
> **Possible Duplicate:**
> How do I specify in which database my schema should be created?

I would like to create an entity module which discuss with another Drupal database.

In my module.install, this is ok :

```
db_set_active('otherdb');
if (!db_table_exists('mytable')) {
$result = db_query("CREATE TABLE mytable (
     id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     title VARCHAR(255)
   );");
drupal_set_message("LOG :Creation of table mytable ok");
}
db_set_active();

```

but this can't be done with hook\_schema :

```
$schema['mytable'] = array (
'description' => 'The main store for our entity',
'fields' => array(
  'mytable_id' => array(
    'description' => 'Primary key for our table of mytable',
    'type' => 'serial',
    'unsigned' => TRUE,
    'not null' => TRUE,
  ),
  'title' => array(
    'description' => 'The mytable title',
    'type' => 'varchar',
    'length' => '255',
    'not null' => TRUE
  ),
),
'primary key' => array('mytable_id'),
);
db_set_active('otherdb');
return $schema;

```

Any ideas ?

# Answer
> 0 votes
I think another angle to attack the problem would be to implement hook\_schema the normal way, as if there was only one database. And then tell Drupal to use another database for some tables in settings.php. Your module will not have to be run on seperate databases and all that external database stuff is taken care of by Drupals database layer.

---
Tags: database
---


title: Unable to change the OG membership type

text:
# Question
Title: Unable to change the OG membership type
I'm trying to add a "restricted" group membership type to only show teasers of a content type to some members. I'm calling the following function from a Rules action; however, the membership ends up being a OG\_MEMBERSHIP\_TYPE\_DEFAULT.

```
function mymodule_subscribe_restricted($account, $group) {
  og_group($group->gid, array('entity type' => 'user',
    'entity' =>  $account,
    'state' => OG_STATE_ACTIVE,
    'membership type' => MYMODULE_OG_RESTRICTED));
}

```

Looking at the source code of og\_group(), the membership type should go through. And it's defined correctly in the db table og\_membership\_type.

Any quick pointers or should I just refactor the whole thing to use a separate group role instead of a membership type?

# Answer
> 1 votes
Found out this is an existing issue with OG 7.x-1.4: http://drupal.org/node/1572480.

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


# Question
Title: Custom URL using Taxonomy and Custom User information (Real Name)
Secondly, in the future I'm looking to organise Users by Taxonomy and having the url path relate to that:

/?q=***taxonomy-tag-here***/***user-fullname-here*** (not username, would be a custom field on the registration form).

How hard would this be to do, are there any modules that can do this, or would I have to create one?

I'm new to Drupal, but I've worked with Wordpress and Joomla a lot in the past and I'm looking to move onto Drupal, so please, be patronising when you explain!

# Answer
You will be able to do quite simply with two modules Pathauto and Token I guess. Token will propose you any field as token and you can use it into pathauto config to generate your urls.
> 1 votes

---
Tags: uri
---


# Question
Title: node_publish_action is not publishing the node
I'm trying to add a submit handler to a "Done" button that should publish a node when the button is pressed. It's a scenario where the Rules module won't cut it, it has to be in code. I tried to following:

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form['#form_id'] == 'my_node_form'){
    if ($form['actions']['done'] !== NULL){
      $user = user_load($form['uid']['#value']);
      $form['actions']['done']['#submit'][] = 'mymodule_publish_submit';
    }
  }
}

function mymodule_publish_submit($form, &$form_state) {
    $nid = $form['nid']['#value'];
    $node = node_load($nid, $vid = NULL, $reset = FALSE);
    node_publish_action($node, $context = array());
}

```

but it's not working. My debug text shows up so I know the submit handler is getting called. Where am I going wrong?

# Answer
> 1 votes
Contrary to this comment on the API documentation, `node_save()` **is** required after `node_publish_action()` is called.

So the submit handler should look like this:

```
function mymodule_publish_submit($form, &$form_state) {
  $nid = $form['nid']['#value'];
  $node = node_load($nid, $vid = NULL, $reset = FALSE);
  node_publish_action($node, $context = array());
  node_save($node);
}

```

As pointed out by jimajamma, the previous code contains a `hook_action()` which allows integration with Actions. The following code does the same thing, but doesn't use the `hook_action()`

```
function mymodule_publish_submit($form, &$form_state) {
  $nid = $form['nid']['#value'];
  $node = node_load($nid, $vid = NULL, $reset = FALSE);
  $node->status = 1; // 0 = unpublished, 1 = published. There are no other states
  node_save($node);
}

```

Pretty simple.

---
Tags: forms, actions, nodes
---


title: Export themes from my site?

text:
# Question
Title: Export themes from my site?
Someone gave me access to a website of theres, and they want me to export the theme from one Drupal 7 install to another.

(I couldn't find any export links on the */admin/appearance* page.)

### How do I export a theme?

# Answer
You will need to have access to the web servers folder structure. You will find the themes inside sites/all/themes, sites/default/themes, sites/YOURSITE/themes or profiles/YOURPROFILE/themes. Once copied to the other Drupal installation it can be enabled under admin/appearance. More on installing a Drupal theme can be found here.

It might be that the theme you are going to copy is a subtheme of another theme. In this case you need both themes. Look inside the THEMENAME.info in your theme and look for the line that starts with base theme =

If a base theme is defined there you need that as well on your target installation.
> 3 votes

---
Tags: 7, theming, importing-exporting, backups
---


# Question
Title: Why is Drupal CSS/JS Aggregation files stored in sites/default/files?
The storing of the CSS aggregation files became problematic for me as our Central Safety Services (CSS) department also tried to store files in the sites/default/files/css folder and everything got wiped out.

Why doesn't it use a root folder, like \[drupal root\]/tmp or /cache or something other than where I store my files?

# Answer
Because the file is served and needs to be accessible via the web server. sites/default/files is typically the default location for uploaded content, or content that is generated dynamically, which these CSS/JS files are.

Your situation happens to be because css (Central Safety Services) happens to be the same directory that Drupal uses to store these files. The recommended solution is to update the path name in the database for their files to something else.

Drupal has the ability to configure the directory where the files are stored, under File System in the admin, but ultimately it has to store them somewhere below Drupal root directory.

```
Drupal 6: http://drupalsitename/admin/settings/file-system
Drupal 7: http://drupalsitename/admin/config/media/file-system

```
> 2 votes

---
Tags: theming, css-js-aggregation
---


# Question
Title: google alerts RSS feed on homepage feed module
I am trying to import a google alert, which I have chosen to be a feed, onto the homepage of a drupal site I am creating.

The goal is to be able to automatically display the results of the rss feed but also to not publish everything right away as I would like to potentially screen the results before they are posted.

I just want to link to the articles respective webpages not necessarily store them as articles within our own drupal site.

I am trying out the module feeds http://drupal.org/node/622696

It might be a lot more than what I need but maybe the only available module. If you know of something better that suits my needs let me know.

I am new to drupal and this module required me to also install:

CTools Job Scheduler

both of those were listed in the readme, but when I went to the modules admin page I was told I was missing:

features views

So I went ahead and installed those as well. Is it normal that I had to install those even though they weren't included in the readme at all?

In any case.. I was able to import a feed but it seems to store all rss feed items as articles.

I also do not see any settings for setting how many posts should be visible, how much content should be shown right away (just want headlines). Although I may need to dig deeper into the code to change this stuff.

I guess what I am really asking is if there is a better/easier way to do what I want.

# Answer
> 0 votes
You should only need Features and Views if you enable the Feeds News module. I think you can import from an RSS feed without that (by changing the Fetcher and Parser settings). However, IIRC, the Feeds News module does automatically create a View interface for you that manages all the feed items from a specific source so it can be handy.

Your setup sounds similar to one I implemented in D6, and it works well for the client. Once the items are imported, use Views to customize the output: a Views block can be configured to show the desired number of posts, titles as links, etc.

You may also want to implement VBO to manage the publishing of the feed items from your administrative page.

---
Tags: 7, feeds
---


# Question
Title: How do exposed views filters make their queries URL safe?
I'm creating my own search form in D7, and I need to sanitize the search text so that it is URL safe. I need to mimic the way that the views module does it because I'm using the search\_api module and views.

In short, I need to make this:

"what is going on around here, anyway?"

look like this:

what+is+going+on+around+here%2C+anyway%3F

How do I do that?

# Answer
Use the url() function to encode your URLs.

```
url("what is going on around here, anyway?");

```

this will return the string `'/what%20is%20going%20on%20around%20here%2C%20anyway%3F'`

You could also use this to get the full, absolute URL.

```
url("what is going on around here, anyway?", array('absolute' => TRUE));

```

You may also be interested in the () function if you need html output.
> 1 votes

# Answer
For future reference, here is what I did:

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

  if ($form_state['values']['area'] == 'cookbook') {
    $search_string = 'http://example.com/cookbook?recipe-search=';
  }
  elseif ($form_state['values']['area'] == 'blog') {
    $search_string = 'http://example.com/blog?blog-search=';
  }

  $search_string = url($search_string . urlencode($form_state['values']['search_value']));

  $form_state['redirect'] = $search_string;
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Does drush sql-sync support inter-db syncing?
Can I use `drush sql-sync` between MySQL and PostgreSQL?

# Answer
> 3 votes
No, you cannot switch database types using `drush sql-sync`. However, the DBTNG Database Migrator tool will do the conversion for you.

---
Tags: database, drush
---


# Question
Title: How to insert a text field inside boolean (single on/off) field in node form
I have created a a content type and I am using it as a registration form to be created by anonymous users.

When I create a field with type of boolean\> single on/off checkbox for my terms and conditions (where it will display the terms and they will be required to check the single checkbox if they agree).

My problem is i want to add another text field for this particular field type in node form for me to put in the text for terms and conditions.

There is a help text box there which i can use, but i used it to display tooltips.

What is the best way to add another text field to boolean type field in node form?

# Answer
> 1 votes
You could implement hook\_form\_alter() and add a suffix or prefix to your field. The suffix and prefix may contain html.

```
    $form['terms'] = array(
      '#prefix' => '<div class="my-class">Something before the field</div>',
      '#suffix' => '<div class="my-class">Something after the field</div>',
    );

```

For a detailed instruction how to write a module that implements hook form alter see this blog post.

There is also a module that can add markup widgets to forms. Checkout Markup.

---
Tags: nodes, entities
---


title: Relation between field of two webform

text:
# Question
Title: Relation between field of two webform
I have created two webform as Vendor and Sponsors.There is two sponsorship type as gold and platinum in sponsors and each vendor is sponsors. Now i want to show in Vendor view the type of sponsorship this vendor have. Both are separate modules. I am not able to understand how to do this.

# Answer
> 2 votes
As far as I know you can not reference a webform submission from another webform. The functionality you describe is needed here is something I recommend using standard Drupal content types for.

Create a content type called Vendor and another one called Sponsor. Use the module Entity reference to create a field that describes the reference between the content types.

Webforms are great for simple forms, surveys etc but not in this use case.

---
Tags: webforms, views, entities
---


# Question
Title: When might a module's weight in the system table not affect its hook order?
I am trying to implement hook\_menu\_alter in my module, but I am finding that revisioning\_menu\_alter is always being called after my hook, regardless of what I set my module's weight to. It seems that this is because the revisioning module does not appear in the system table at all, even though it is enabled.

What is going on? How can I make my module's hook get called after revisioning's hook? Don't modules always have to have an entry in the system table?

# Answer
If revisioning does not appear in the system table, it is considered not installed and hook implementations it provides are not executed.

Upon installation, the revisioning module updates its weight to 1, making its hook implementations run later than those of most other modules (which default to a weight of 0).

If you want to change the order in which implementations of a particular hook are executed, have a look at hook\_module\_implements\_alter().
> 2 votes

---
Tags: 7, routes
---


# Question
Title: Migrating single drupal instant to a multi-site thats live
I am having a drupal site developed and ready on my local server which is a standard drupal Installation. Back on server I have a multisite setup with 3 sites all using same database with different prefix for each site. Now I want to move this site that is on local server to replace one of the site in the multi-site online.

I am confused with the following things:

* How do I export the db from a single instant and import it on server? I only have phpmyadmin access. And all sites in multisite use same db and is prefixed.
* How do I export the db from localhost with the required prefix.
* Does the multisite db use all the tables I have in single instant?
* Will importing the local tables to multi-site db overwrite the tables thats already there or will I have to delete the tables online first and then import?

What are the best steps to follow for my problem, I saw many conflicting info online and in this community. As I am doing this on a live site, dont wan't to break it.

# Answer
On the local machine:

1. Execute `SHOW TABLES` to get a list of tables.
2. Copy the table names into a text file, one table per line.
3. Use your favorite tool to transform the lines from

`tablename`

to

`RENAME TABLE tablename TO prefix_tablename;`

Choose a table prefix different from the ones you have on the server. This ensures that no tables are overwritten when you import them to the server.
4. Execute the resulting script on the DB of your local installation.
5. Edit the settings.php to use the chosen table prefix.
6. Export the local database. You can use Backup and Migrate but you have to make sure to also export the structure of the cache tables, but not the content. You can also use phpMyAdmin, but you should empty (not delete) the cache tables and the watchdog table first. These tables can get quite large and their content is not essential to the operation of a drupal site.

On the server:

1. Import the SQL file of the backup into phpMyAdmin. This creates the necessary tables and fills them with the contents from you local machine. If the file is large, you might run into issues with `max_execution_time` and `upload_max_filesize`.
2. Create a new subdirectory under the sites directory and copy your local settings.php file into it.
3. Copy any modules, themes and file uploads required by your local site to the server.
4. Copy `sites/example.sites.php` to `sites/sites.php`. The file `sites/sites.php` allows you to map Drupal sites to arbitrary paths within the sites directory. Read the comments in that file for details.
5. Edit `sites/sites.php` so that the URL of the site to replace points to your new directory within `sites`.

Now you can make further adjustments to your new site without damaging the old one. Problems are usually caused by different locations of modules, themes and uploaded files. These problems cannot be solved by a simple search and replace on the database, because of the way Drupal stores some configuration information (serialized PHP arrays or objects). You might want to switch the site to maintenance mode while fixing such problems.
6. In case of panic, remove sites/sites.php and you have your old site back.
> 3 votes

---
Tags: 7, migrations, multi-sites
---


title: Devel query log not showing all queries

text:
# Question
Title: Devel query log not showing all queries
I've enabled the Devel query log, and it's logging most queries as expected. However, I've got this module which connects to another database and executes a few queries against that one. All queries goes through db\_select(), db\_query(), db\_insert(), db\_delete() or db\_update().

However, queries executed against the other database (connection is configured on the fly, and not through the settings.php file) never appears in the query log.

Any way I can make it work, so that ALL queries appear in query log at the bottom of the page?

**Note**: Caching does not seem to have anything to do with it. I've cleared all caches, returned to the page, and still no queries appear in the query log.

# Answer
> 3 votes
It's because Devel uses the `Database::getLog()` static method to get a list of the queries that have run for the page.

That method can only be run for a single connection at a time, and Devel specifically requests logs for the 'default' database connection (see `devel_shutdown_real()`):

```
$queries = (devel_query_enabled() ? Database::getLog('devel', 'default') : NULL);

```

In short you've got 2 options that I can think of:

1. Edit the devel module file directly, forcing it to loop through all available connections and combine the query logs (obviously hacking contrib modules is not recommended though)
2. Implement your own logic in a custom module and have a second set of query logs appear at the bottom of your page. The `devel_shutdown()` function and `devel_shutdown_real()` should give you all the code you need to get started if you go down this route.

---
Tags: 7, database
---


# Question
Title: Webform email component created programmatically
I am trying to build an email confirmation utility into a web application. For some other project I might just use jQuery to insert a new text field beneath my email field and compare their input as soon as the user finishes typing into the created textfield.

The problem is the email authentication will fail if a user does not have javascript enabled on his/her browser.

**To overcome this problem, I want to use code to programmatically create and insert a second textfield immediately after the actual email field and compare their input when the user submits.**

What I don't know is what webform hook(s) I can use to create an email component.

Can anyone help with some information and/or code samples, please?

# Answer
```
$email = array(
  'nid' => $node->nid,
  'email' => 'name@example.ch',
  'subject' => 'default',
  'from_name' => 'default',
  'from_address' => 'default',
  'template' => 'default',
  'excluded_components' => array(),
);
webform_email_insert($email);

```

Check this post for more info.
> 1 votes

---
Tags: 7, webforms, emails, users
---


# Question
Title: Change page.tpl template inside a hook_menu callback
I have a hook\_menu like that:

```
function mymodule_menu() {
    $items['mymodule-test'] = array(
        'page callback' => '_mymodule_test_callback',
        'access callback' => TRUE
    );
    return $items;
}

```

and the callback function:

```
function _mymodule_test_callback()
{
    // processing
    return $html;
}

```

I googled around but i cant find how to force the page template inside my \_mymodule\_test\_callback function.

**Edit: why i cant (or dont feel comfortable with) url-based suggestion**

Url-based suggestion are easy to implement, however they can not completely fit my needs.

The template I have to use is determined in the \_mymodule\_test\_callback function, according to very various aspects, for example:

1. Does exists a node of type 'foo', and does the field 'abc' value's be 'xyx'? =\> choose template 'page-mymodule-foo.tpl.php'
2. The node does exists, but the field 'abc' value is empty? =\> Choose temlate 'page-mymodule-bar.tpl.php'
3. The node does not exist at all, but the user has the 'bimbumbam' role? =\> Choose template 'page-mymodule-foobarz.tpl.php'

...and so on.

I know this is a rare behavior, and that i could redirect instead of switching template, but actually the function body is not big and i prefer to do this way.

Is not possible?

# Answer
> 1 votes
You cannot directly change the page template from a page callback. You can either bypass the full page rendering by printing your page content from your page callback. Or you can use a global variable to trigger addition of template suggestion in `hook_preprocess_HOOK` implementation.

```
function _no_template_page_callback() {
  // ... processing ...
  // Print the result, and bypass the page template (so no blocks, no CSS, no JavaScript, etc.).
  print $html;
}

function _template_suggestions_callback() {
  global $MODULE_page_template_suggestions;
  // ... processing ...
  // Set flag to trigger usage of our custom page template.
  $MODULE_suggest_page_template = $suggestions;
  return $html;
}

function MODULE_preprocess_page(&$variables) {
  global $MODULE_page_template_suggestions;
  if (!empty($MODULE_page_template_suggestions)) {
    // Use template suggestions set from _template_suggestions_callback the module.
    foreach ($MODULE_page_template_suggestions as $suggestion) {
      $variables['template_files'][] = $suggestion;
    }
  }
}

```

---
Tags: 6, theming, routes
---


title: Execution of complex db Queries in tpl

text:
# Question
Title: Execution of complex db Queries in tpl
What is performance cost of executing queries like EntityFieldQuery directly in tpl.php files ?

I have some situations, where i have put db queries and more complex php logic in various tpl.php files.

It works, but my concern is performance. What are best practice ? Should i move those queries somewhere else and what are advantages ?

Thanks!

# Answer
To be honest you should never, ever run an SQL query inside a template file. This sort of thing should be handled either at the preprocess level, or even better, at an earlier stage in the page build (usually in a custom module file). There are good reasons for this:

1. Putting business/application logic inside a template file is never a good idea. Literally reams of volumes have been written on the subject; over the past few years MVC has been the 'it' pattern so I'd recommend reading up on that to understand the reasoning behind this kind of separation.
2. If you execute queries in your template files they will run even for pages for which the rest of the page content has been cached, which is a definite performance no-no.

I imagine there are other good reasons not to do it as well, suffice to say these are two quite strong arguments for moving the logic out of your template files.
> 2 votes

---
Tags: database, performance, theming
---


title: Dynamic page content

text:
# Question
Title: Dynamic page content
How can I include body content on a dynamically generated page?

The page in question is defined in `hook_menu()`. I have successfully given it a title but I don't know how to give the page text content.

# Answer
I think you're just looking for a standard `page callback` for your menu item. To extend the example from the `hook_menu()` docs slightly:

```
function mymodule_menu() {
  $items['abc/def'] = array(
    'page callback' => 'mymodule_abc_view',
  );
  return $items;
}

function mymodule_abc_view() {
  $text_content = 'Text to print to the page.';

  // You could just return the string itself here, that will also work fine,
  // but it's 'best-practice' to return a render array so other parts of the system
  // can alter the content if they so desire.
  return array(
    '#markup' => $text_content
  );
}

```

Remember to clear Drupal's caches after making the changes to `hook_menu()`, or they won't be picked up.
> 0 votes

---
Tags: 7, nodes
---


title: drupal_goto argument retrival

text:
# Question
Title: drupal_goto argument retrival
I am redirecting my users with the following code:

```
drupal_goto("event/registration/failed",
    array(
      'query' => array('nid'=>$submission->nid, 'sid'=>$submission->sid),
    )
);

```

On the target page I am executing the following function:

```
function _event_registration_failed($nid, $sid){
  dsm($_REQUEST);

  drupal_set_message("TESTING NID: {$nid}");
  drupal_set_message("TESTING SID: {$sid}");
}

```

My the variables in the drupal\_set\_message calls do not have any data. But, the $\_REQUEST object above has the data I expected.

**Is there a correct way to access argument passed with drupal\_goto or is it correct to use the $\_REQUEST object array?**

# Answer
> 1 votes
Query arguments are available in `$_GET`. Drupal doesn't handle those query arguments for your menu callback; the only query argument Drupal automatically handles is `$_GET['q']`, which is the path for the requested page.

By default, `$_REQUEST` contains the contents of `$_GET`, `$_POST` and `$_COOKIE`. Drupal uses `$_GET` for the requested page path, and I would rather use `$_GET` also in this case, just to avoid possible conflicts.

In your case, those query arguments are accessible with `$_GET['nid']`, and `$_GET['sid']`.

If you define the menu handler with code similar to the following one, then your menu callback gets those values as arguments.

```
function event_menu() {
  $items["event/registration/failed/%/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($nid, $sid) {
  // …
}

```

You could get the node object, instead of the node ID, if you use the following code.

```
function event_menu() {
  $items["event/registration/failed/%node/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($node, $sid) {
  // …
}

```

---
Tags: 7, redirection, views
---


title: Moving title into Content Type node?

text:
# Question
Title: Moving title into Content Type node?
I'm currently building my first Drupal theme (have experience in other content manager systems) and just have a quick question regarding normal practice...

So, I have a number of different templates for a website theme I am building

Home \> Level 1 \> Level 2 \> Article

I have created Content Types for each of the different templates e.g

\*node--level\_1.tpl.php\*, \*node--level\_2.tpl.php\*

By default it seems that the page's title is printed in page.tpl.php.

My plan is to delete the title from page.tpl.php and render it where appropriate within the node templates.

My question is simply is this ok? Is this normal practice? And are there any implications/consequences of doing this?

It's worth saying the reason for doing this is that on some levels there is no title, and often when the title exists it has to rendered under an image (so printed under the custom image field).

Obviously one issue I instantly thought of is that for default pages such as /user the title won't be printed. Could I use some logic in page.tpl.php to say print the page title only if it is not printed within the content type node template?

Thanks for your time!

Scott

# Answer
I'd say go ahead - your plan to remove the Title from the page template and print it instead in the node template makes sense to me. I've done similar things in the past.

One thing you may want to look into is creating a custom page template for your content types, in addition to your node templates. This will give you even more control over your final rendered page on a per-content-type basis. This could help you avoid inadvertently removing the title from other pages, eg. your Front page.

Here's a quick function you can add to your theme's template.php file that will get Drupal to look for a custom page template (eg. \*page\_*node*\_yourcontenttype\* for each content type.

```
/**
* Tell Drupal 7 to look for a custom page template for each node type.
*/
function YOUR_THEME_NAME_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
        $suggest = "page__node__{$vars['node']->type}";
        $vars['theme_hook_suggestions'][] = $suggest;
    }
}

```

Please note that I didn't write this particular snippet, but I have done the exact same thing successfully. Check out http://leepowers.net/drupal-node-custom-content-type-page-template (not my site) for the original snippet with a nice explanation.

Hope that helps!
> 4 votes

---
Tags: nodes
---


# Question
Title: Get directories & files of a theme in module
How can I scan a directory and its files from a module? Is there any permission issue? I have to apply some logic based on the folder structure in the active theme.

When I use the below code, its returning empty

```
file_scan_directory($path,$depth=0);

```

I am getting the path to theme by below code:

```
$path = base_path() . drupal_get_path('theme','sandesh').'/'.'layouts';

```

Is this the wrong method to this? Or is there any other apis for that.

# Answer
You are mixing filesystem path and URL path:

* `base_path()`: Returns the base **URL** path (i.e., directory) of the Drupal installation.
* `drupal_get_path()`: Returns the path to a system item (module, theme, etc.).

The second argument for `file_scan_directory()` is the `preg_match()` regular expression of the files to find. You are using '0' which only match a single file named '0'.

`file_scan_directory(DRUPAL_ROOT . '/' . drupal_get_path('theme','sandesh') . '/' . 'layouts');` is all you need to do. Use `base_path()` only when building URL for which an existing helper function (`url()`, `file_create_url()`, etc.) cannot be used.
> 3 votes

# Answer
I think your problem has to do with using web paths instead of filesystem paths.

`$_SERVER['DOCUMENT_ROOT']` will have the path that your sites is stored in on the server, eg /var/www/html. You should then be able to concatenate this with the results from `drupal_get_path` to get the read directory. You will likely need to play with adding / at places in the path.

You may also be able to use `DRUPAL_ROOT` instead of `$_SERVER['DOCUMENT_ROOT']`, but I don't quite recall if they are always equivalent. You could also potentially use `__DIR__` from within the theme or module.
> 0 votes

---
Tags: 7, files
---


title: Issues with the devel module

text:
# Question
Title: Issues with the devel module
After I install the devel module I can no longer configure any blocks, I get an internal server error. I uninstalled and the issue stopped, re installed and its an issue again.

Furthermore, I cannot see the grey box in the lower left hand side of the browser where I can access all the variables available in a given page. This is the main reason for attempting to use the module. The module is successful in printing all SQL queries at the bottom of the page however. Any insight as to what might be wrong?

Update: I can also no longer uninstall the devel module from within the drupal backend, i receive the same error when trying to access the uninstall page, I will have to remove it manually from the file system

Update: Removed the devel module once again and problem is gone...

# Answer
Based on your comment about the 500 error and the menu entry problems, I suspect that the problem isn't really with the Devel module, but rather with your server.

Take a look at your Apache `error_log` to see what is causing the 500. Following the steps for fixing a WSOD may also help.

A total guess is that you are running out of memory, and this is happening during the menu rebuild phase when you have an empty cache. Enabling the Devel module likely was just the tipping point and now you are seeing memory problems. You can try increasing the `memory_limit` and see if that fixes things. But, you really do need to look at the error logs and find the true cause of the 500 errors.
> 1 votes

# Answer
i'm getting the same error, I installed the module and when I try to configure it on the admin/config/development/devel I get this error: "The conexion was restablished".

In admin/reports/dblog I get this message Notice: Undefined offset: 1 in mysite\_process\_table() (line 2139 of /var/www/html/sites/mysite.com/modules/custom/hotsite/hotsite.module).

the mysite\_process\_table()

function mysite\_process\_table() {

$arg = arg(1);

$items = explode('-', arg(1));

$ids = array();

foreach ($items as $item) {

$temp = explode('=', $item);

array\_push($ids, $temp\[1\]); //THIS IS THE LINE 2139

}

foreach ($ids as $pos =\> $id) {

$pos++;

$update = db\_update('save\_l')

-\>fields(array('save\_l.poss' =\> $pos))

-\>condition('id', $id)

-\>execute();

}

}

¿some advices?
> 0 votes

# Answer
I was experiencing a similar issue and came across this question.

After enabling Devel and its option "Display $page array", I was getting a 500 error when I tried to reach /admin/modules/. I had to remove the Devel directory to get back into /admin/modules/. (If I also enabled Devel Themer, I was also getting a the "white screen of death".)

Disabling "Display $page array" resolved my issues.

EDIT: I also posted about this on drupal.org and was told the cause was a low php memory\_limit setting in php.ini. The link: http://drupal.org/node/1759394
> 0 votes

---
Tags: 7, debugging
---


# Question
Title: Mobile website translation problem (losing language prefix)
I have site translations that works with language prefix

m.mysite.com/ - default language (lithuanian)
m.mysite.com/en - english
...

If i translate site to foreign language and pushed menu button on mobile website, it redirects to the default language.
For example, if I were in **m.mysite.com/en** (website translated in english) and pressed button "News" it redirects me to **m.mysite.com/news-page** that is in default language.

I should redirect to **m.mysite.com/*en*/news-page** that is translated in english and has language prefix /en/.

So, how to add language prefix to the link and redirect correctly (without losing current site translation)?

# Answer
We've come across a similar problem in our site on a desktop platform. So far, we've discovered the following about links in Drupal (for example, the `href` on an `<a>` tag in a Block Body):

* If you use a link without a preceding `/`, Drupal will replace the last url element with your link name (i.e. `mysite.com/en/area1/thing1` will become `mysite.com/en/area1/thing2` when a user clicks a link configured as `href="thing2"` on a page in `area1`).
* If you use a preceding `/` in your link, Drupal appends it to the domain directly (i.e. `href="/thing2"` directs to `mysite.com/thing2`).

We leveraged this to make language prefixes work, with limited success. As long as all our links are within the same uri path (i.e. all links on pages within `area1` go to `area1` pages), the language prefix is preserved. Once you try to leave that path, though (i.e. `href = "/area2/thing3"` on a page in `area1`), you must use the `/` and lose the language prefix. For those pages, you'll need to add URL aliases. We're still looking for a module/solution that saves us the time and effort of aliasing our menu system and cross links.

Note that in any case the base url (`mysite.com`) is preserved, so you should get the same results regardless of your platform (mobile or desktop).
> 0 votes

---
Tags: i18n-l10n, theming
---


# Question
Title: I am unable to install module for my Drupal 7
I am a newbie to Drupal and was trying to develop a website. I am in need of modules to enhance and when trying to install them , it throws the following error.

> Warning: ftp\_login(): Login incorrect. in FileTransferFTPExtension-\>connect() (line 59 of ..)
> Check Username and Password

My username and password are perfect. Can someone please help??

# Answer
The alternate way to install module is to download the module and untar/unzip the files under **/drupal/sites/all/modules/**

Using Admin UI you can enable the module.
> 3 votes

---
Tags: 7
---


# Question
Title: How do I make the select options have a textfield beside them instead of a box?
I created a webform that uses dynamic select options generated from a specific content type, which represent objects. I would like to have a text field beside each one to in which the user can input the desired quantity of the object.

I have tried looking this up on Google but to no avail. How should I go about doing this? Is there a module or a specific way by which I can implement this?

Thanks for reading this.

# Answer
> 0 votes
You can build your own custom Form api element looking at select other example http://drupal.org/project/select\_or\_other and the documentation for it form api element is at http://drupal.org/node/1158654

---
Tags: webforms
---


title: Simple conversation wall

text:
# Question
Title: Simple conversation wall
I want to create a simple wall, where user can post some text, and other users can reply on it. It can be done without ajax or with. I have made few modules before, but now i am stack with this part, how to create a page(which i can link into menu) on which i can post message, and then watch the list of this conversations+comments, should i use Views module? any examples would be the way.

here is example of that wall,

# Answer
> 2 votes
Check this out http://drupal.org/project/facebook\_status. Also if ur on D7 then https://drupal.org/project/statuses

---
Tags: views
---


# Question
Title: Move code from template file to custom module
I would like to move portions of code from template files to custom module. But i fail do find descriptive guide for such task. Idea is to migrate complex db queries and EntitiyFieldQuery out of the tpl.php files. For example:

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'predmet_clanak')
  ->fieldCondition('field_taxonomy_choose', 'value', 1 , '=')
  ->fieldCondition('field_vrsta', 'tid', 241);

$result = $query->execute();
$nodes = entity_load('node', array_keys($result['node']));
foreach ($nodes as $node) {
  print ('<div class="putujuci-wrapper"><div class="putujuci">');
  print drupal_render(node_view($node, 'teaser'));
  $nodelink = ltrim(url('node/' . $node->nid), "/");
  print ('</div>');

  $imageLink = '<img src="' . $base_url . '/sites/all/themes/profil_edu/css/images/vise-button-static.png" width="55" height="28" border="0" class="img-swap">';
  print l($imageLink, $nodelink, array('query' => array('iframe' => 'true', 'width' => '800', 'height' => '700', 'format' => 'popup'), 'attributes' => array('class' => t('colorbox-load gumb')), 'html' => TRUE));
  print ('</div>');
}

```

This code fetches collection of nodes (when conditions are met) in custom tpl.php file. I have been advised not to create complex queries in tpl files, but do not know yet best practices to do so.

I guess, module will firstly need to know context where i want this to occur? And after i do this in the module, do i need to pass this to the template.php first?

# Answer
I think you should go through the module developer guide.

You can use `hook_preprocess_HOOK()` in your template.php. So if your code was placed in the node template, the hook will be `themename_preprocess_node($vars)` and then you can check for a particular node type and create a variable like `$vars['custom_variable'] = 'the query stuff';` and this variable will be available in your template.
> 2 votes

---
Tags: theming, database, performance
---


# Question
Title: Add a node as a select list in Webforms Drupal 6?
I want to make a Webform in Drupal 6 where I can put a `<select>` list where the lists are a node. I already created a content type which is `events` and these events expires. So what I want is when the user submits a form he/she has the ability to select from the `<select>` list so when the form is submitted, when I go to the submission results, I can see the content type(`events`) which the user chose upon submitting the webform. Is this possible? Thanks

# Answer
> 1 votes
If you are using D6 then consider the Webform View Reference Component module. Here is a quote about it (from the module's project page):

> ... adds a webform component where you could use a View as a datasource for your normal webform select component. Instead of hardcoding all the selectable values in the component values field you just select a reference to a View similar to the CCK nodereference. The selectlist/radiobuttons/checkbox then automatically gets filled with all the nodes from the View.

---
Tags: webforms
---


# Question
Title: How to build an Email Diggest using Rules
I am building a Website using Drupal 7. This website contains events, event-comments and event-registrations (=Registrations module):

* Event
    + Event Comments
    + Event Registration

Now I need to inform users by email when:

* New events are created
* Existing events are changed/updated
* Events are deleted
* Event Comments where added
* Somebody register for an event
* Somebody unregistered of an event

I found the Rules module can trigger actions on these events and conditions.

BUT: I need to generate a digest/newletter with the above information once all day or half a day etc. so users don't get too much emails ;-)

Advanced (but optional) features:

* If a user un-register from an event don't send him any more updates on this particular event.
* Users can set their digest/newsletter interval in their profile. eg. once a day, once an hour, etc.
* Maybe other content-types then events will be added to the digest system later.

Questions:

1. How to I best build such a digest/newletter email using Rules? What additional modules can be integrated to Rules to address this?
2. Can Rules-Scheduler by of any help for this?
3. Is there another email-module that can to this out of the box without Rules?

# Answer
You may want to consider Notifications or Subscriptions. Both modules offer either immediate or digest notifications for content updates. Be aware that Notifications currently requires PHP 5.3.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: show fields after adding joins in hook_views_query_alter
I managed to programmatically add tables/joins in `hook_views_query_alter()` like this:

```
$td_join = new views_join();
$td_join->table = 'taxonomy_term_data';
$td_join->field = 'tid';
$td_join->left_table = 'audience_node_og_mvh_ti';
$td_join->left_field = 'tid';
$td_join->type = 'inner';

$query->add_relationship('audience_node_og_mvh_ti_td', $td_join, 'node', 'audience_node_og_mvh_ti');

```

When I go to edit the view and check the "auto preview" I can see that the generated query is correct:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, audience_node_og_mvh.title AS mvh_title, audience_node_og_mvh_ti_td.name AS field_data_field_cv_node_entity_type
FROM
{node} node
inner JOIN {field_data_group_audience} audience_node ON node.nid = audience_node.entity_id
inner JOIN {og} audience_node_og ON audience_node.group_audience_gid = audience_node_og.gid
inner JOIN {node} audience_node_og_mvh ON audience_node_og.etid = audience_node_og_mvh.nid
inner JOIN {taxonomy_index} audience_node_og_mvh_ti ON audience_node_og_mvh.nid = audience_node_og_mvh_ti.nid
LEFT JOIN {taxonomy_index} audience_node_og_mvh_ti_audience_node_og_mvh_ti ON audience_node_og_mvh_ti.nid = audience_node_og_mvh_ti_audience_node_og_mvh_ti.nid
inner JOIN {taxonomy_term_data} audience_node_og_mvh_ti_td ON audience_node_og_mvh_ti_audience_node_og_mvh_ti.tid = audience_node_og_mvh_ti_td.tid
WHERE (( (node.status = '1') )AND( (node.type IN  ('johndoe')) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

```

But somehow I can't figure out how the new fields in the query (the ones from the joins) can be shown in the view itself.

Does anyone know how to do this?

# Answer
If you want view to show your fields, you should not use a `hook_views_query_alter`. instead you should implement `hook_views_data()` to describe your `audience_node_og_mvh_ti` table to view and be able to use its columns as fields when building your views using the UI.

You can however access your view's query results in an `hook_views_pre_render()` implementations to add your additional field to the output.
> 2 votes

# Answer
If the data is in the views result row object then you can use the customfield module.

http://drupal.org/project/views\_customfield

You have to create a php field and you have access to the $data object for each row. So what you can use it to do a return "string"
> 0 votes

---
Tags: views
---


# Question
Title: How should I structure a multiple-value Field Collection where each value is uniquely named?
I have a content type for a collage of six photos. For each photo there is a caption, a link, some link text, and the photo itself. The photos are of different sizes and in different places, and there can be only one photo in each spot per collage.

If I just use Field Groups, I have to create a different CCK field per photo per field, for a total of 24 fields.

If I use a single level of Field Collections I can get that down to six separate Field Collections and four CCK fields, but if I need to make a change that applies to all six photos, I have to make the change six times.

I can use two levels of Field Collections, with a main Collection that contains the four fields, and six other Collections named "Top Left", "Top Right", etc., each of which contains only the main Collection. This is maximally abstracted and would probably do, but it makes the node editing interface look like this:

Those redundant fieldsets are bothersome and are a dead giveaway that the underlying data is architected badly.

Using a single Field Collection that allows multiple values seems the most correct. It gets me down to one Field Collection and four fields. But the repeated groups don't have any identifying information other than their deltas, and if the client ever needs to add one they won't be able to keep track of which line corresponds to which spot in the collage.

Is there a way for me to put identifying information on each of the repeated values of a field or Field collection? Otherwise, is there a better way for me to do this?

# Answer
Finding no acceptable answer, I ended up just creating 24 separate fields and six field groups to contain them. Horrible in many ways, but with the benefit of actually working.
> 0 votes

# Answer
You could simply add an additional field called "Location or Type" to the field collection with the various options. Then you can use that field in a view block to filter by, or even more simply in your node.tpl.php file.
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: How can I add a class to a block with code (development)
For theming reasons I'd like to add a specific class at the "block" level to some of the blocks I'm generating with a custom module. I know there is a module block class, but I would rather like to do it directly in code (there is no need to change is afterwards).

I also know of hook\_block\_view\_alter, but that does not seem to allow adding or editing classes.

Is it possible to add a class with to a block from within my module code? I'm using Drupal 7.

# Answer
@flocondetoile's answer is OK, but the correct way is using drupal\_html\_class().

```
function YOURMODULE_preprocess_block(&$variables) {
  $variables['classes_array'][] = drupal_html_class('your-custom-class');
}

```

The function can be used from a module, or a theme.
> 3 votes

# Answer
Simply, you could use a preprocess function.

```
function YOURTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] ==  'ID-YOUR-BLOCK') {
    $vars['attributes_array']['class'][] = 'YOUR-CLASS';
  }
}

```
> 3 votes

---
Tags: 7
---


# Question
Title: create online "diagnostic" questionnaire with results based on choices
Is this possible to achieve in drupal 7? The example I found is here http://www.hairloss-research.com/alopecia-areata-diagnosis/

I tried to use webform module or quizz module but no luck. Thank you for answers.

# Answer
> 1 votes
Maybe this helps: Module for decision tree / guided entry. There is nothing which appears do the job out of the box. So you need to evaluate the modules if they full fill your needs. I am going to check following modules to build a so called decision tree:

---
Tags: webforms
---