# Question
Title: Complex Drupal setup using Views, Entity/Node Reference and custom content type
OK, here is my setup, i will then explain what im trying to achieve:

I have a content type of DELIVERY another content type of BOOK and another content type of FEEDBACK

Now, any given user can have anywhere from 1 to 12 DELIVERY content types created (these are created using Rules automatically when they sign up). I use the Node Reference field to attach a BOOK to the DELIVERY content type, if the user has more than 1 delivery content, i will be attaching different books to each delivery content each month. When i attach a book to the users delivery, they can then create a FEEDBACK content to leave feedback under that particular DELIVERY.

So for example,

```
User 1
  - Delivery 1
       - Book 1
       - Book 2
  - Deliver 2
       - Book 3

```

I want the user to be able to create a Feedback content and select the relevant book that the feedback belongs to and once saved it should appear under the particular delivery content.

How can I achieve this?

# Answer
You should be able to add a node reference field on the **Feedback** content type. When your user creates a new **Feedback** node, they should be able to select the correct **Delivery** node to associate it with.

You will most likely want to constrain the user's selection options to **Delivery** nodes associated with that particular user so that User 1 doesn't leave feedback about User 2's delivery. One way to do this is to create a custom autocomplete function and use `hook_form_alter()` to edit the **Delivery** node reference field on the **Feedback** node create/edit form.

On a **Delivery** node, to display **Feedback** nodes that are associated with that **Delivery** node, you can create a View that has shows **Feedback** nodes that are associated with the currently logged in user and references the current node nid (use contextual filters for both).
> 0 votes

---
Tags: views, nodes, entities
---


# Question
Title: PHP to show if content has new comments in taxonomy-term.tpl.php?
Is it possible to add some PHP to taxonomy-term.tpl.php that will look and see if any content tagged with the term has new comments, and if so print something in the html?

# Answer
> 0 votes
Yes you can but it will it performance without proper caching. Don't do that in tpl because you can cache it, even with page cache. Code look something like that using drupal api.

```
<?php
$has_comment = false;
$nids taxonomy_select_nodes($term->tid);
foreach($nids as $nid){
$node = node_load();
  if($node->comment_count > 0){
    $has_comment = true;
  }
}

```

# Answer
> 0 votes
You'll have to determine what you mean by "new" comments. Perhaps you mean comments posted within the last 24 hours? 48 hours? If so, then you would want write a preprocess function in your theme using `template_preprocess_taxonomy_term()`. Perhaps something like this:

```
/**
 * Implements template_preprocess_taxonomy_term().
 */
function demo_preprocess_taxonomy_term(&$variables) {
  $term = $variables['term'];
  $tid = $term->tid;
  // These are all the nodes that have the current taxonomy term.
  $referenced_nodes = taxonomy_select_nodes($tid, false);

  // Only keep going if there is at least one node that has the term.
  if (!empty($referenced_nodes)) {
    // Find comments posted within the last 24 hours.
    // @see comment_get_recent().
    $query = db_select('comment', 'c');
    $query->addTag('node_access');
    $query->fields('c')
          ->condition('c.status', COMMENT_PUBLISHED)
          ->condition('c.created', time(now) - 60*60*24, '<=');
    $comments = $query->execute()->fetchAll();

    // Only keep going if there is at least one comment that fits our criteria.
    if (!empty($comments)) {
      $comment_nids = array();
      foreach($comments as $comment) {
        $comment_nids[$comment->cid] = $comment->nid;
      }
      if (!empty($intersection = array_intersect($comment_nids, $referenced_nodes)) {
        // Add all the comments in $intersection to something like $variables['comments'].
        // Then in your taxonomy-term.tpl.php, you can check if $comments is empty.
        // If not, then render the comments.
      }
    }
  }
}

```

Note that I have not tested this code, so please treat it as pseudo-code that you'll need to tweak.

---
Tags: 7, theming
---


# Question
Title: Is it good practice to style the panel layout?
I have a panel layout. I was wondering if its okay to apply additional css ids / classes to this or to style elsewhere? I am using panels everywhere and I have moved the layout into my theme.

# Answer
> 2 votes
It's perfectly acceptable to add CSS ids and classes to panel layouts.

---
Tags: panels, theming
---


# Question
Title: programmatically add an existing entity reference autocomplete field in custom form
I need to create a custom form and add an entity reference field to it. The field uses autocomplete with a view for entity selection. The field already exists on a node but i also need it in a custom module. Is there a way to add this field in a custom module with `MYMODULE_MYFORM_form()`?

# Answer
> 1 votes
If you are using the references module's node\_reference field, then, in your custom form, you'll want to create a field that uses the node\_reference's autocomplete, like so:

```
$form['referenced_field'] = array(
  '#title' => 'Referenced field title',
  '#description' => t('Referenced field description.'),
  '#type' => 'textfield',
  '#autocomplete_path' => 'node_reference/autocomplete',
  '#required' => TRUE,  // Optional depending on your circumstance.
);

```

See node\_reference.module line 892 for more details on parameters, etc.

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


title: How to controll rss feed in D7?

text:
# Question
Title: How to controll rss feed in D7?
Could anyone please tell me that how to control RSS feed in D7, because even without my knowledge D7 has created a RSS feed for my site.eg `http://wwww.mysite.com/rss.xml`

Even though in that feed my page contents are not selected but some un-nessaary items are selected like News letter, Poll and image jCarousel details. I'm 100% sure that I didn't select these items to generate feed but I don't understand how get it involved.

Also if I want to select the required page content link to display on the RSS feed how can I do that ?

# Answer
> 1 votes
By default, all nodes opted to "Promoted to front page" will be shown in the global feed.

This is a per-node setting, and you can control the default value at **Admin \> Structure \> Content Types \> \[type\] \> Edit**.

Also, if you want to take control which fields (and each field's display) should be shown in the feed, as a feed item, go to "Manage display" tab at the node type edit page and enable `RSS` custom display. There you can hide/show fields of the feed.

You can, as an advanced step, override this page with a View (see default taxonomy and front page/feed views) or even unset the menu router item completely with a custom module, implementing hook\_menu\_alter.

There is a module, RSS Permissions, that you can restrict access to feeds if you are interested.

# Answer
> 1 votes
To default RSS feed page goes for example every node with promote to front page flag set to true.

You can use Views to create your own, highly configurable RSS feeds. If you want even more control you can use this module https://drupal.org/project/views\_rss.

You can override default RSS feed with a Views one too

---
Tags: 7, feeds
---


# Question
Title: How to get Views Criteria Filter arguments inside Views API hook?
My question is related to:

https://drupal.stackexchange.com/questions/70551/how-to-sort-view-by-taxonomy-multiple-value-field-with-a-range-of-only-selected

I have an idea, but I didn't manage to find a way to get arguments passed to Views Filter Criteria.

I would like to get them inside hook\_views\_pre\_render

Could someone give me any advice?

# Answer
> 1 votes
Ok, I found it.

In $view-\>filter property is an array of views filter handler objects. In selected object inside $hander-\>value array are arguments passed to this filter.

---
Tags: 7, views
---


# Question
Title: What are the issues with overriding nodes with views?
I am thinking that I have a couple of content types that views would be better at displaying my content. e.g. If an image field is blank, show this default image (this is only a basic example where a view would be preferred over Drupal's default node. i.e. I want to create a view with the node id as an argument and set the views page path to node/%. Are there any drawbacks to this?

# Answer
You *could*, however, do something like this in `node.tpl.php`:

```
<?php if ($node->type=='FANCYTYPE'): ?>
  <?php print views_embed_view('name_of_fancy_view', 'default', $node->nid); ?>
<?php else: ?>
  // the rest of the normal node.tpl.php stuff here
<?php endif; ?>

```

or create a `node-TYPE.tpl.php` (D6) or `node--TYPE.tpl.php` (D7) with just the Views logic inside.
> 1 votes

---
Tags: views
---


# Question
Title: Using Views for a custom table with multi-value fields
I have a custom table with two columns - the primary is simply entity IDs (nids), and then there is a data column, but it it can be a multi-value (from 1 to anything).

How can I structure the MySQL table and create a view that will blend a list of entities (nodes in my case) with data from the custom table without losing their multi-value character (probably using relationship)? Basically I need to achieve that next to a node with a given field I can also show data (separated by commas or otherwise) from the multi-value column from my custom table.

There is some excellent help about doing this with single-value columns at Using views with a custom table/schema but I guess it is a bit more tricky with multi-values.

# Answer
You'll probably need 2 MySQL tables (to overcome the many-to-many relationship): one to link the nids to data-ids and one to link the data-ids to the actual data. One with three columns and the other with two: (primary key, nid, data-id) and (data-id, data).

```
    +------------+-----+--------+     +---------+--------+
    |nid-data-id | nid | data-id|     | data-id | data   |
    +------------+-----+--------+     +---------+--------+
    |1           | 1   | 1      |     | 1       | value  |
    |2           | 1   | 2      |     | 2       | value  |
    |3           | 2   | 1      |     +---------+--------+
    +------------+-----+--------+

```

This way you can use either multi-select or new values every time. Linking these tables can be done in the same manner as the article you provided (linking two can be found at Views - join tables or the views table API ) but I do not have any experience with that.
> 0 votes

---
Tags: 7, views
---


title: Set up Mailhandler with IMAP Gmail

text:
# Question
Title: Set up Mailhandler with IMAP Gmail
I can't figure out how to configure Mailhandler with an IMAP Gmail account locally with MAMP.

I've been following the recommendation at http://drupal.org/node/207366#gmail and it is never working fine. The test mbox that ships with the module works just fine.

My settings are:

* Protocol: **IMAP**
* Folder: **INBOX**
* Domain: **imap.gmail.com**
* Port: **993**
* Username: **username@gmail.com**
* Password: **mypassword**
* Extra commands: **/ssl**

I've tested different combinations like:

* Switch **imap.gmail.com** to **gmail-imap.l.google.com**
* Changed port to **995** or **587**
* Trimmed username to "username" only (w/o @gmail.com)
* Switched /ssl by **/ssl/novalidate-cert**, /tls, /notls...

Most of these attempts were without any conviction and only because the default config wouldn't work and return the following error when saving:

```
Warning: imap_open() [function.imap-open]: Couldn't open stream {imap.gmail.com:993/ssl/novalidate-cert}INBOX in MailhandlerPhpImapRetrieve->open_mailbox() (line 118 of /docroot/sites/all/modules/mailhandler/modules/mailhandler_php_imap/plugins/mailhandler/retrieve/MailhandlerPhpImapRetrieve.class.php).

```

And this error when hitting "Test connection":

```
Mailhandler could not access the mailbox using these settings

```

Any idea what I'm missing to make this work ok?

P.S. : I can ping imap.gmail.com or telnet on port 993 just fine.

# Answer
Unfortunately, MAMP (even the Pro version) basically provides no support for G-mail. For evidence, look at the comments on the official guide on the MAMP blog.

Although I haven't tried it, one of the comments suggests this solution.

And here's another way to set up postfix on Lion without relying on MAMP.

I too use MAMP, and instead of working with mailhandler I use the SMTP module instead, which allows Drupal to send messages locally independent of the local mail configuration.
> 1 votes

# Answer
The issue here is the "locally with MAMP." the imap\_open() command is relying on the imap php library (http://www.php.net/manual/en/ref.imap.php). Which can either be compiled with or without SSL support. MAMP, and MAMP PRO do not come with an ssl imap, so, the only way to get around this and make IMAP work with SSL (which is what is required for google apps/gmail) is to compile the IMAP extension for yourself.

This (https://www.activecollab.com/forums/topic/5844/) is where I got the following information. Hopefully this is helpful:

Snow Leopard Server has PHP 5.3 built-in (hooray!), but without the IMAP module (drat!). There are several guides out there that have partial solutions to the problem, but most ask you to build your own Apache and PHP apart from the OSX native. I wanted to use as much native OSX as possible. One blog in particular was the easiest solution (with a few minor corrections in the blog comments). Here are all the instructions, in order, with all the corrections inline:

1 Open a Terminal session from OSX

2 Download and unpack the latest IMAP source code (2007f as of this writing):

cd ~/Downloads

curl -o imap.tar.gz ftp://ftp.cac.washington.edu/imap/imap-2007f.tar.gz

tar -zxvf imap.tar.gz

3 Build IMAP libraries and copy to correct locations:

cd imap-2007f/

make osx EXTRACFLAGS="-arch i386 -arch x86\_64 -g -Os -pipe -no-cpp-precomp"

sudo mkdir /usr/local/include (optional)

sudo cp c-client/\*.h /usr/local/include/

sudo mkdir /usr/local/lib (optional)

sudo cp c-client/\*.c /usr/local/lib/

sudo cp c-client/c-client.a /usr/local/lib/libc-client.a

4 Download and unpack the source code of whatever version of PHP you are using. I was using 5.3.14

cd ~/Downloads

curl -o php.tar.gz http://us.php.net/distributions/php-5.3.14.tar.gz

tar -zxvf php.tar.gz

5 We only need the source for the IMAP extension, so there's no need to compile all of PHP.

cd php-5.3.14/ext/imap

phpize

--The following info is system dependent. I was on snow leopard so this worked for me. You might have to look this up somewhere else. MACOSX\_DEPLOYMENT\_TARGET=10.6 CFLAGS="-arch i386 -arch x86\_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch i386 -arch x86\_64 -g -Os -pipe" CXXFLAGS="-arch i386 -arch x86\_64 -g -Os -pipe" LDFLAGS="-arch i386 -arch x86\_64 -bind\_at\_load"

./configure --with-imap=/usr/local/imap-2007 --with-kerberos --with-imap-ssl=/usr/

6 If you received errors (specifically, a complaint about OpenSSL's evp.h), you may need to adjust the path at the end of "with-imap-ssl" to /usr/include or /usr/include/openssl. The above worked for me, using Snow Leopard 10.6.8.

7 Now make the module:

make

8 If you didn't receive an error, go to the next step. If you received an error about pcre.h (notably on MAMP instead of Snow Leopard Server), you need to copy some files from the downloaded PHP source

sudo cp ../pcre/pcrelib/pcre.h /usr/include/php/ext/pcre/

make

9 And now we copy it into our extensions directory. Your directory might be named differently, depending on what version of php you have configured.

sudo cp modules/imap.so /Applications/MAMP/bin/php/php5.3.14/lib/php/extensions/no-debug-non-zts-20090626/

10 You may have to add the following to your php.ini file, but I have a hunch that extension=imap.so is already there:

extension=/Applications/MAMP/bin/php/php5.3.14/lib/php/extensions/no-debug-non-zts-20090626/

11 Restart apache
> 1 votes

---
Tags: emails
---


# Question
Title: Re-use value entered in component in previous webform page on following page in markup
I'm creating a webform with multiple pages. On the first page, I ask for "Name" (textfield), and on the second page, I would like to have a markup component that incorporates the value entered for "Name" on the first page.

I have tried using webform's token system in Webform 3.x and the new token functionality in Webform 4.x, as well as hook\_form\_alter(), all to no avail.

In regard to the later, in glue.module I defined:

```
function glue_form_alter(&$form, &$form_state, $form_id) {
  if (preg_match("/webform/i", $form_id)) {
   dsm($form);
  }
}

```

and the resulting array displays the "name" component value (from page one) as empty on page two.

Would someone please help me?

# Answer
> 3 votes
For one I would be wary of matching $form\_id like that. It means you will be altering any webform you might add in future. Plus it is possible for other form id's to contain webform, for example webform\_node\_form, which is the node add/edit form for the webform content type. There is also webform\_components\_form, webform\_component\_edit\_form and probably lots of others.

If you really want to regex it I would use webform\_client\_form\_\d+

However if I wanted to do all webforms I would use hook\_form\_BASE\_FORM\_ID\_alter(), like this:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function hook_form_webform_client_form_alter(&$form, &$form_state, $form_id) {

}

```

and to do just one webform I would use hook\_form\_FORM\_ID\_alter(), like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_webform_client_form_922_alter(&$form, &$form_state) {

}

```

Now for your actual question, you can accomplish this in form alter:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_webform_client_form_922_alter(&$form, &$form_state) {
  // If we are on the second page.
  if ($form['details']['page_num']['#value'] == 2) {
    // You can get the value via the submitted_tree using the field key.
    $name = $form_state['values']['submitted_tree']['name_field_key'];
    // However I would recommend instead using submitted.
    // The reason is that with fieldsets the submitted_tree gets more complex,
    // and also, users can change the field key (who knows why that's allowed)
    // so that is unreliable. The submitted array uses the webform field cid
    // so it won't change.
    // (1 is the id of my name field)
    $name = $form_state['values']['submitted'][1];

    // There are 2 main ways you can add the markup.
    // 1. If you actually have a webform markup component on the second page
    // and you want to set its value. This means you can control the field via
    // the webform UI.
    // I use check plain because this is data entered by the user and needs to
    // be sanitised. You could also use filter_xss() if the field might
    // contain HTML.
    $form['submitted']['markup_field_key']['#markup'] = '<div class="my-markup-field">' . check_plain($name) . '</div>';
    // 2. If you don't have a webform markup component and just want to add
    // markup in, you can do this, just using regular form API.
    $form['submitted']['my_markup_field'] = array(
      // Defaults to type #markup.
      '#markup' => '<div class="my-markup-field">' . check_plain($name) . '</div>',
      '#weight' => 10,
    );
  }
}

```

---
Tags: webforms
---


# Question
Title: Show if there are 'new' comments on a view of terms?
I have comments on nodes that are categorised by terms. I need to show a view of the terms and if there are any new comments in any of the nodes that term is tagged with.

So if I have the following:

```
Term1
-NodeA (has new comments)
-NodeB (has new comments)
Term2
-NodeC (no new comments)
-NodeD (no new comments)
Term3
-NodeE (no new comments)
-NodeF (has new comments)
Term4

```

I need my view to look like this:

```
Term1 – new comments!
Term2
Term3 – new comments!
Term4

```

First I tried making a view of comments to include the new comments field and using relationships to show the terms. However if a term has no nodes or comments (Term4 in my example) I need the term to still be displayed.

So I then tried making a view of the terms. I added the relationships 'Taxonomy term: Content with term' and the field 'Content: New comments' which uses this relationship. This does show the number of new comments as expected. It gives me duplicated results (which I may be able to fix with grouping fields) but unexpectedly it also hides the terms that have no comments or nodes.

Am I going about this the right way and if so how can I stop the 'empty' terms being hidden?

UPDATE Ive updated D core and a few modules that had new versions (but not views). The view works fine with the relationship of 'Configure Relationship: Taxonomy term: Content with term' when the field is 'Content: Title (Title)'. However when I add the field 'Content: New comments' then terms that have no comments are hidden.

UPDATE Ive tried the following in a views field:

```
if(intval($data->node_new_comments) > 0) {
  if(!array_key_exists($data->tid, $static)) {
    print "new comments !";
    $static[$data->tid] = 1;
  }
} else {
  print "here you do whatever you want when there's no new comment";
}

```

UPDATE - by 'new comments' I mean comments that the logged in user hasnt read. This is a standard field in views. I need this rather than an arbitrary date cut off. Sorry for any confusion.

# Answer
> 1 votes
This works for me. I have a term view that shows the term name field and my code adds the new comment flag after the term name.

The code goes in a custom module.

You need to change to VIEW\_NAME to your view name and the TAXONOMY\_FIELD\_NAME to the name of your field (like field\_tags for example).

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  global $user;
  if ($view->name == 'VIEW_NAME' && $user->uid) {
    // Get all the tids of the views results.
    $tids = array();
    foreach ($view->result as $result) {
      $tids[] = $result->tid;
    }

    // Get all the tids that have recent comments.
    // Only return terms that relate to nodes that have not been viewed by
    // the current user since the last comment.
    $query = db_query("SELECT t.TAXONOMY_FIELD_NAME_tid
                         FROM {node_comment_statistics} c
              LEFT OUTER JOIN {history} h ON c.nid = h.nid AND h.uid = :uid
                   INNER JOIN {field_data_TAXONOMY_FIELD_NAME} t ON t.entity_id = c.nid
                        WHERE c.comment_count > 0
                          AND t.TAXONOMY_FIELD_NAME_tid IN (:tids)
                          AND (h.timestamp IS NULL OR h.timestamp < c.last_comment_timestamp)",
               array(':uid' => $user->uid, ':tids' => $tids));
    $commented_terms = $query->fetchCol();

    // Loop through the results and add the new comments flag where necessary.
    foreach ($view->result as &$result) {
      if (in_array($result->tid, $commented_terms)) {
        $result->taxonomy_term_data_name .= ' new comments!';
      }
    }
  }
}

```

# Answer
> 0 votes
You have to make another query first, to retrieve the terms which have nodes with new contents.

I've been helped by this thread.

As I told you, I put all this in php fields ; if you have the time, it'll be better to put it in a module, in a views\_query\_alter or else.

1. Add a **php field**, and in the **setup code**, go grab the tids' list of terms which have new content :

```
$query = db_select('node_comment_statistics', 'c')
  ->condition('c.last_comment_timestamp', 'history_user.timestamp', '>');
$query->join('field_data_YOURTERMREFERENCEFIELD', 't', 't.entity_id=c.nid');
$query->fields('t', array('YOURTERMREFERENCEFIELD_tid'))
  ->groupBy('t.YOURTERMREFERENCEFIELD_tid');

$static = $query->execute()->fetchCol();

```
2. Now in the **output code**, check that your term is in this array :

```
if (in_array($data->tid, $static)) {
  print 'new comments !';
}

```

This is the lightest I see, even if the query can be heavy if you have a large amount of nodes and comments.

EDIT: I have to recall that **putting php in the sql with views php is NOT a good practice**, I invite you to put all that in a custom module in hook\_views\_query\_alter as soon as you can.

# Answer
> 0 votes
Adding the 'Content: New comments' field adds an `INNER JOIN` to the node\_comment\_statistics table, which can potentially be the source of the problems you're experiencing. (For example, if there's no entries for NodeC, NodeD and NodeE in node\_comment\_statistics for some reason, the terms will not be shown due to the `JOIN` being an `INNER` one.)

Does rebuilding node\_comment\_statistics help?

# Answer
> 0 votes
Here's a sketch of an answer that'll get you most of the way there, I think. Start by creating a view of nodes, then add the taxonomy and the latest comment time as fields.

Now turn on aggregation for the view, and set the aggregation for the taxonomy field to be "group results together", on the column "tid".

Change the aggregation setting for the comment time field to be "Maximum".

You should now have a view which lists all your taxonomy terms (at least those that have content) with the last comment date. The final step will be to process the comment timestamp in a views hook or theming to make it display as you require, which should be relatively simple.

---
Tags: views
---


# Question
Title: how to apply .active class to only one menu item that uses optional filters
I have an exposed a filter to a page like so in drupal: http:example.com/user?profile=12 There is a menu entry for this specific link in a block in the sidebar. Is there a way drupal can add the .active class to the link with this specific url. Currently the active class is applied to links with this pattern: http://example.com/user?profile*

Which happen to be all links in that block.

# Answer
A page with optional filters set in the url is not treated as a new different page, hence the .active class is applied on all pages with the same pattern. Use of a contextual filter such that the path changes to something like:

> http://example.com/user/1

will fix this problem, since each new url will be pointing to a new page.
> 0 votes

---
Tags: routes, views
---


# Question
Title: Where is root directory in Drupal Acquia Desktop?
With other systems it's www or htdocs, but what about with Acquia Desktop?

# Answer
It depends on your system; on Macs, it's in `home/Sites/acquia-drupal`.

To see where the files are for a site:

1. Open dev desktop.
2. Click settings.
3. Click the *Sites* tab.
4. Highlight the site you want to check and click *Edit*.
5. The site path will be displayed.
> 2 votes

# Answer
Acquia desktop allows you to use any folder you wish as your root folder hence your site could be on the desktop, or documents. Use the import new site option in the settings tab to point to where drupal folder is located
> 3 votes

---
Tags: 7
---


# Question
Title: Adding conditional statements to custom text fields in views
I have custom text fields set to display two items as follows:

> \[field\_title\]: \[field\_subtitle\]

Is there a way I can get rid of the colon if the subtitle field has no value? via php or javascript?

# Answer
Sure.

1. Edit both fields -- `[field_title]` *and* `[field_subtitle]` -- so that both are "exluded from display"
2. Edit `[field_subtitle]`, and select *Rewrite the output of this field*
    1. In the box for the rewritten value, enter `: [field_subtitle]`
    2. Make sure *Hide rewriting if empty* is checked at the bottom
3. Create a third field whose type is *Global: custom text*
    1. Unlike the first two existing fields, do **not** check the *Exclude from display* box -- leave this one visible
    2. In the *Text* box for that field (the value), enter `[field_title][field_subtitle]` (no spaces in between)

Hope that helps... :)
> 6 votes

---
Tags: views, entities
---


# Question
Title: hook_form_alter building dynamic textfields
In hook\_form\_alter I am fetching data from the database. Some of the data has several textfields, lets say addresses. People can have several addresses.

How can I pass the count of rows to my form, and have it rendered with the row count?

I try to do the following in hook\_form\_alter

```
function personalinfo_form_alter(&$form, &$form_state, $form_id) {
    $i = 0;
    foreach ($arr as $value) {
        $form['personal'][$i]['address']['#value'] = $value;
        $i ++
    }
    $form_state['num_names'] = $i;
    }

```

And in my function personaladdresses($form, &$form\_state) , where the texfields are actually build

I want to use $form\_state\['num\_names'\] to do a for/while loop to build the textfields with the addresses.

But it seems that hook\_form\_alter is called AFTER the for/while loop, so it will never get the correct value from $form\_state\['num\_names'\]

how can I pass a value to my form function before the for/while loop?

# Answer
> 0 votes
You should use following code in the form. It will display the array structure in $form\_state\['values'\] in form\_submit.

```
$form['#tree] = TRUE;

```

---
Tags: 7, forms
---


title: Removing header region

text:
# Question
Title: Removing header region
I am completely new to drupal. I am trying to customize the Acquia Marina theme to suit my upcoming site. The original layout is as shown in the screenshot:

I want to remove the white band that is the header region and move the logo and title down to the blue band right below it. Basically, have the blue strip function as the header. Is that possible. I have tried removing the `header` and `header-top` regions from the info file but that did not make any difference.

# Answer
You need to change the html structure for this. Open page.tpl.php then remove the header section from there.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Commerce: How to save user data (in the order date) when delete it
Hi all for one of my client site I use Drupal Commerce.

Now: when an user make an order his/her uid and email are stored in the order's tables (I don't know which one, but this is not important) and this is ok.

When the user (or the administrator) delete his/her account all orders related to this user lost account information so in commerce there are orders without uid and email, and this is not good: How to know which is the client that have bought the order XYZ ?

How can I resolve this problem ? Is there the possibility to not delete this information. Other commerce suite like Prestashop op Magento do not have this problem.

M.

# Answer
Interesting question.

Though I have never worked with Magento or Prestashop(I have made a simple site with it), so I don't know how they deal with it.

At first I saw your question two days ago & I didn't give much thought about it but today I came again & thought, why do we expect a contributed module to do everything for us? We all have to set our own store & can have different requirement...

Commerce Guys are great & have worked so hard to keep it tight with drupal as well as followed the same way which drupal has done to leave hooks for extending it anywhere you want..

You will have to make your own module for this & will have to play around a bit. It would be very interesting I promise.

There is a hook as I remember `hook_commerce_checkout_complete()` to get all the info of a order when you are going through checkout. You can pass `$order` variable as parameter here & it will have all the value related to current order. You can check like --

```
function MYMODULE_commerce_checkout_complete(){
  dpm($order);
}

```

Now go for buying anything on your instance and see what you get.

So the next you will do is...you can retrieve more data if you want(like user data if it exists in case of authenticate user or what ever you want to save for next) and save it in your own table. Once you get data...there are many things which you can do now...make your own listing page by executing query or...expose your table to views so you get to feel the power of it for your own data too...

And as this is your table...removing your user or in case he deletes his account will never have any effect on this..GOOD!!
> 0 votes

---
Tags: commerce
---


# Question
Title: exception 'TwitterException' with message 'Bad Request'
I am trying to setup twitter module for Drupal 7 on my localhost. I followed the installation instructions as given in Twitter 7.x installation guide. I followed steps until "Add Twitter accounts" when i start getting this error.

```
Could not obtain a valid token from the Twitter API. Please review the configuration.

```

The dblog has the following information:

> exception 'TwitterException' with message 'Bad Request' in C:\wamp\www\test\_twitter\sites\all\modules\twitter\twitter.lib.php:142 Stack trace: #0 C:\wamp\www\test\_twitter\sites\all\modules\twitter\twitter.lib.php(101): Twitter-\>request('https://api.twi...') #1 C:\wamp\www\test\_twitter\sites\all\modules\twitter\twitter.lib.php(51): Twitter-\>auth\_request('https://api.twi...', Array) #2 C:\wamp\www\test\_twitter\sites\all\modules\twitter\twitter.pages.inc(336): Twitter-\>get\_request\_token() #3 C:\wamp\www\test\_twitter\includes\form.inc(1464): twitter\_auth\_account\_form\_submit(Array, Array) #4 C:\wamp\www\test\_twitter\includes\form.inc(860): form\_execute\_handlers('submit', Array, Array) #5 C:\wamp\www\test\_twitter\includes\form.inc(374): drupal\_process\_form('twitter\_auth\_ac...', Array, Array) #6 C:\wamp\www\test\_twitter\includes\form.inc(131): drupal\_build\_form('twitter\_auth\_ac...', Array) #7 C:\wamp\www\test\_twitter\sites\all\modules\twitter\twitter.pages.inc(130): drupal\_get\_form('twitter\_auth\_ac...') #8 \[internal function\]: twitter\_user\_settings() #9 C:\wamp\www\test\_twitter\includes\menu.inc(517): call\_user\_func\_array('twitter\_user\_se...', Array) #10 C:\wamp\www\test\_twitter\index.php(21): menu\_execute\_active\_handler()
>
> # 11 {main}

I also have oauth module installed as given in the requirements.

Additional info:

* My machine accesses internet via a proxy server and i do have proxy settings given in settings.php file. Not sure why it should cause problems.
* I was able to run twitter API commands using twitteroauth library in a standalone application. It was throwing errors before i gave it the proxy settings for curl.

Can anyone help?

# Answer
> 1 votes
I actually had a lot of trouble setting the Twitter module up on my localhost for testing, so I just created a blog post about how to set that up, that includes some tips on doing this with localhost: http://drupalwoo.wordpress.com/2013/04/22/how-to-show-tweets-from-your-twitter-account-on-your-drupal-website/

Here are the couple of things that I think my be relevant for you to check:

1. If you’re testing on localhost, use the following urls for your website and callback URLs (don’t worry, these are just placeholders, and your drupal site will send the correct callback URL when it connects):

```
Website URL: http://127.0.0.1:8000/twitter/oauth
Callback URL: http://127.0.0.1:8000/twitter/oauth

```
2. If you’re still getting errors when testing with localhost, make sure the version of the module you’re using has the patch #5 on this issue queue: http://drupal.org/node/1924478#comment-7260928 (if you have an older version of the module, prior to the incorporation of the patch, get the latest stable/dev release that includes it and uninstall and install the module)

# Answer
> 0 votes
There is some change in twitter api. I was also facing some issue while connecting twitter. The Patch has been applied by the module maintainer and so either update your module or go through this issue and apply the patch. This patch works fine http://drupal.org/node/1924478#comment-7260928

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


title: Update status behind a proxy

text:
# Question
Title: Update status behind a proxy
I'm running Drupal in an intranet which is behind a simple HTTP proxy. I'd like for the module and core update checks to actually work.

I seem to remember there was a core hack to do this on Drupal 6, but I can't find the page anymore.

Does anyone know how I can get this working?

# Answer
> 6 votes
One of our corporate installations had a forward proxy that prevented direct access to the internet, we ended up patching core with 'the proxy patch' (thus named this way because this issue has been open since 2004 - http://drupal.org/node/7881).

http://drupal.org/node/7881#comment-4134240 \- has a patch for drupal 7 http://drupal.org/node/7881#comment-2446280 \- has a patch for drupal 6

Once the patch is installed, then you will be able to alter drupal\_http\_request() to send all queries through the proxy.

This way all modules that require access to the internet will function as expected, e.g. update statue, aggregator, openID etc

**UPDATE**: The patch is already merged in Drupal 7 trunk ( https://drupal.org/comment/6425278#comment-6425278 ), and hopefully will be out with Drupal 7.16

# Answer
> 2 votes
For reference, this is the syntax you can now use in Drupal to configure it to run behind a proxy (from default.settings.php/7):

```
/**
 * External access proxy settings:
 *
 * If your site must access the Internet via a web proxy then you can enter
 * the proxy settings here. Currently only basic authentication is supported
 * by using the username and password variables. The proxy_user_agent variable
 * can be set to NULL for proxies that require no User-Agent header or to a
 * non-empty string for proxies that limit requests to a specific agent. The
 * proxy_exceptions variable is an array of host names to be accessed directly,
 * not via proxy.
 */
# $conf['proxy_server'] = '';
# $conf['proxy_port'] = 8080;
# $conf['proxy_username'] = '';
# $conf['proxy_password'] = '';
# $conf['proxy_user_agent'] = '';
# $conf['proxy_exceptions'] = array('127.0.0.1', 'localhost');

```

# Answer
> 1 votes
There's a module for that

It's currently only Drupal 6, but should provide a good starting point.

# Answer
> 1 votes
For resolving staging pbs, I'm working locally with the real production domain name, but behind a proxy, so that drupal installation and web server configuration are strictly identical (on some conf the IP listening could be different, depending on the listening ip in production).

So, I had a proxy responding for http://mydomain.local, proxying to http://www.mydomain.tld, but on a local IP.

Whith nginx, in local vhost conf :

```
server_name  mydomain.local;
set $proxied_server_name www.mydomain.tld;
set $proxied_cookie_domain mydomain.tld;

# then generic proxy conf
proxy_set_header Host              $proxied_server_name;
proxy_set_header X-Real-IP         $remote_addr;
proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;

# My param added for drupal absolute url construction
proxy_set_header X-Proxy-Host      $host;

# For headers rewriting (Location or Refresh)
proxy_redirect   http://$proxied_server_name/ http://$host/;

proxy_cookie_domain $proxied_server_name $host;
# and for drupal auth, with cookies without sub-domain
proxy_cookie_domain $proxied_cookie_domain $host;

```

For the proxied vhost, just like in production

```
server_name  www.mydomain.tld;

```

And in my settings.php

```
if (isset($_SERVER['HTTP_X_PROXY_HOST'])) {
  $base_url = 'http://' .$_SERVER['HTTP_X_PROXY_HOST'];
}

```

With this conf, I can sync all drupal files AND database AND server configuration between a lot of drupal installation (dev and production in my case but could be whatever you want).

---
Tags: 6, updating, proxies
---


# Question
Title: How often does drupal core need updating?
How often (on average) does drupal core need updating?

# Answer
> 5 votes
There is no "rule" but update as soon as it's released.

Usually Drupal core updates (bug fixes) are released once in a month but in case of a security vulnerability, there will be an immediate release.

I usually leave Update Status module enabled and configured to check for new releases every week.

Read more about Drupal core release cycle here. (This is about major Drupal releases, eg. 6, 7 and upcoming 8)

---
Tags: 7
---


# Question
Title: How can I quickly re-save all users on my site?
Very similar to this question except I need to save users, not nodes.

Use case: I added a field (single boolean) to a feature so that the field is added to user profiles. I then pushed the feature to my staging server. However, existing user accounts do not have the default field value for this field assigned. Re-saving each account fixes the problem, but there are 1000 users.

How can I quickly re-save all users on my site?

# Answer
You can use the "Execute arbitrary PHP script" bulk operation in VBO and when you run it enter:

```
user_save($entity);

```

You could also run this PHP (you can do so by enabling the devel module and going to devel/php on your site):

```
set_time_limit(0);
$uids = db_query('SELECT uid FROM {users} WHERE uid != 0')->fetchCol();
$users = user_load_multiple($uids);
foreach ($users as $user) {
  user_save($user);
}

```

If you don't have many users you shouldn't need the time limit line.

Also, Clive mentions that field\_attach\_update is faster. To use that replace the user\_save line with field\_attach\_update('user', $user)
> 8 votes

# Answer
rooby's answer is probably the easiest/quickest method but just to offer a code solution that can be used with VBO...

You can define your own action to save the user like this:

```
function MYMODULE_rules_action_info() {
  return array(
   'MYMODULE_update_user_account' => array(
     'label' => t('Save a user account'),
     'parameter' => array(
       'account' => array(
         'type' => 'user',
         'label' => t('User'),
       ),
     ),
     'group' => t('MODULENAME'),
   ),
 );
}

function MYMODULE_update_user_account($account) {
  user_save($account);
}

```

Once you've clerared the caches you should see your new action appear under VBO/rules and anywhere else actions are used.

Edit: It seems this might re-inventing the wheel somewhat if VBO will already let you do it natively, but it's a nice simple example of a rules action so I'll leave it here in case anyone needs it. Plus it removes the need for `eval()` to be used which is never a bad thing.
> 5 votes

---
Tags: users, views, batch-operations
---


# Question
Title: Drupal 7 website with landing page and two sections with different templates
I need a Drupal 7 website with 2 sections..

for eg. www.example.com

One is Civil and the other is MEP.

Landing page with navigation to the below two sections:

**section 1: www.example.com/Civil**

**section 2: www.example.com/MEP**

Screen shots of the design:

Landing page:

Site -a

Site-b

The exact requirement is as follows:

```
/ = intro page

/site-a/ = menu and templates for site a

/site-b/ = menu and templates for site b

```

Separate layout and menu for these two sections. How can we keep two layout for the two sections? Is it a multisite? or just two sections?

Please suggest me a solution.

# Answer
> 0 votes
I think, you want to create two different website with the same domain name and same admin section.

You can add a taxonomy "site" field in all content type in the site and separate the content for both site using the taxonomy "site" field.

You can set different theme for both site using the module Themekey.

Now, you need to create three different theme, one for main website (www.example.com), second for (www.example.com/Civi) and third for (www.example.com/MEP).

You can use the views module to display the content for specific site (civil or MEP).

# Answer
> 2 votes
These sites look almost identical. In fact, I would say that given the pictures, the layouts are close enough to use the following templating strategy:

In Drupal, it's very easy to create a front page that will be your landing page. You will simply create a template file called page--front.tpl.php and put whatever html you want in here, exactly like you want to lay it out. This will be what people see when they come to example.com/

I know we keep calling these 'sites' but they are pages instead. Indeed 'site-a' and 'site-b' will be two 'Basic Pages titled 'Civil' and 'MEP'. In my mind these are so close I would simply have have one layout template (page.tpl.php) with the same regions, etc. It looks like the only difference is in the content. So, to handle that I would use blocks and Drupal's default functionality to force blocks to appear on one page and not others.

So far you would have to templates - page--front.tpl.php for the home page and page.tpl.php for all other pages. In the event you indeed wanted to have a different layout for pages Civic and MEP you could even have templates for these. If Civic had a node ID of 3, for example, and MEP of 4, the template names would be page--node--3.tpl.php and page--node--4.tpl.php. Please see the Drupal theming guide for more details.

**Site-a menu and site-b menus:**

You will have two menus created for site-a and site-b. There will be blocks for each in the Blocks section under structure. You will put both blocks in the same region (say, 'menu-region' if that's what you decide to call it). Then, edit one block to 'appear only on the following pages' and type in:

```
site-a
site-a/*

```

Then, edit the other block to 'appear only on the following pages' and type in:

```
site-b
site-b/*

```

Drupal will automatically know which menu to load. Also, each of these blocks will have their own css tags in the markup, so it will be easy to style them.

For the other sections, you would repeat the process - add all the blocks you need to appear in one regions, but edit them to show or not show based on what site (page) you are on.

---
Tags: theming, multi-sites
---


# Question
Title: Create Latest Comments View Per Group OG 7.2
Hello it has been a while since i used OG Groups (and Panels) and im struggling a bit to create a view for the group home page showing the latest comments within the group. Its all to do with the Relationships and Contextual Filters. There seems to be so many relationships and filters available to me that its making me struggle a bit.

Could anyone advise me on how to make a view that will display the comments for that group? I think once i see the Relationships used there will be no holding me back from various other things.

Thanks

# Answer
> 0 votes
OG membership: OG membership from Node for the relationship and OG membership: OG membership from Node as the contextual filter not forgetting to sort the validation criteria

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


title: POST content on redirect

text:
# Question
Title: POST content on redirect
I would like to redirect my users to the login page on certain pages when they are not logged in. I have created a custom template for my login page, I don't know if that makes a difference, but I would like to pass two bits of information to the page in a way that the user can't see them.

I would like to pass a message that should be displayed on the login page and also the URL that the user should be directed to after login. What is the easiest and most clean way of doing this please?

# Answer
Have you tried rules module. You can trigger custom action on some event. What you need to do :

1. create an event "when the node being viwed"
2. create a condition "when node is equal to some node"
3. Fire a action "redirect to login page"
4. Fire another action "show a message"(this is set drupal\_set\_message for you)
> 2 votes

---
Tags: 7, redirection
---


# Question
Title: How to create a custom Date Formatter for grouping in Views?
I have a view of content type "event". One of the fields is a category of the event which is a taxonomy list and i have a field for the date and time the event takes place.

Now i have set up the view showing the events in a time period i can set through an exposed filter, grouping the events by their date-field (nr.1) and as a second group field by the category (nr.2).

I am sorting this view with the event-field (ascending) as the first sort criteria and `Taxonomy term: Weight` as the second sort criteria.

It works as designed, but every event that shares the same time on a given date creates an own group row:

Like this:

* Category-Name
    + 4/12/2013
        - Event1 12.00h
        - Event2 12.00h
    + 4/12/2013
        - Event3 13.00h
    + 4/12/2013
        - Event5 14.00h
        - Event6 14.00h

What i want to achieve is this:

* Category-Name
    + 4/12/2013
        - Event1 12.00h
        - Event2 12.00h
        - Event3 13.00h
        - Event5 14.00h
        - Event6 14.00h

Question: is it possible to have a **formatter** that has stripped out the time, so i can group by date only?

Of course i tried a custom display **formats** for the date beforehand, but this doesn't affect the grouping.

**EDIT:** the hint about the RDF module helped partly with this issue. I could remove the extra markup in the date field. Nevertheless the sorting of the date field still takes the time of the event into account. There's another sorting i didn't mentioned in the first place, cause I didn't expect it to be relevant.

The location of an events is referenced as entity and also added to a row of an event and sortet by title (asc). Now the date-field is superceding the title of the location, because the event-time is still taken into account.

I had started another question on this other issue, but actually think it belongs here. I still need to strip out the time somehow...

# Answer
> 2 votes
Views uses the rendered value for the field, including the field wrappers to do grouping. In your case, views is treating each date field differently.

There are 3 ways this can be fixed. One of the following methods should do it.

1. Remove the tags from the rendered output.
2. Using a custom template and a preprocess function, you can strip all markup and print the output only.

1. views-view-fields.tpl.php
    2. template\_preprocess\_views\_view\_field
3. Turn off the RDF module. Views will take care of the grouping itself. The RDF module adds extra metadata to your markup, which makes views separate the grouping as shown in your example above instead of grouping the similar dates together.

# Answer
> 0 votes
Under the `format` settings you can set a field to group the rendering on.

This screencast Learn Views with NodeOne, part 16: Grouping fields shows how to group fields, which is hopefully helpful.

The grouping doesn't care at all for the formatter, which I think is correct behavious, so going down that route won't be helpful.

There are also related complex options called aggregation, check out Learn Views pt 28: The aggregation setting.

---
Tags: 7, views
---


# Question
Title: Add class to top-level ul using menu_block
I am using the Menu Block Module to generate my main and sub navs. I want to add a class to the ul for **just the top level of the main nav**.

As I understand it, I can do something like this:

```
function theme_menu_tree__menu_block($variables) {
  return '<ul class="my classes">' . $variables['tree'] . '</ul>';
}

```

or this:

```
function theme_menu_tree__menu_block__main_menu($variables) {
  return '<ul class="my classes">' . $variables['tree'] . '</ul>';
}

```

**However, that seems to wrap every level of the navigation with the above html. How can I restrict the modification to the first level?**

It doesn't look like I am given much data in `$variables`. Am I missing something?

# Answer
> 8 votes
Here's the trick: theme\_menu\_tree\__MENU\_NAME() and theme\_menu\_link().

```
<?php
/**
 * Implements theme_menu_tree().
 */
function THEMENAME_menu_tree__MENU_NAME(&$variables) {
  return '<ul class="FIRST-LEVEL-CLASS">' . $variables['tree'] . '</ul>';
}

/**
 * Implements theme_menu_link().
 */
function THEMENAME_menu_link__MENU_NAME(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Wrap in dropdown-menu.
    unset($element['#below']['#theme_wrappers']);
    $sub_menu = '<ul class="OTHER-LEVEL-CLASS">' . drupal_render($element['#below']) . '</ul>';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
?>

```

# Answer
> 1 votes
`$variables` gives me:

```
array(3) {
  ["tree"]=> string(n) "HTML for the sub-tree"
  ["theme_hook_suggestion"]=> string(n) "menu_tree__menu_block__main_menu"
  ["theme_hook_suggestions"]=> array(0) { }
}

```

It seems pretty bad, but I could do a string search to see if the menu contains the text for one of my top level elements:

```
<?php

function theme_menu_tree__menu_block__main_menu($variables) {
  if (!stripos($variables['tree'], 'home')) {
    return '<ul>' . $variables['tree'] . '</ul>';
  } else {
    return '<ul class="my classes">' . $variables['tree'] . '</ul>';
  }
}

?>

```

# Answer
> 0 votes
You might be interested in this recent blog post regarding themeing native menus in drupal by Webbykat (as opposed to menu\_blocks). He is adding classes to `theme_links`, which your not trying to call. He's modifying the tpl file, but you could do this in `YOURTHEME_links__system_main_menu()` I believe. I've used this function as well, but offhand not to achieve this.

```
<?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix', 'main-menu')), 'heading' => array('text' => t('Main menu'),'level' => 'h2','class' => array('element-invisible')))); ?>

```

> Fact 4: You can control the classes applied to each menu ul in the menu region tpl (depending on your theme, presumably).
>
> To add a class to the ul of the main menu, you would modify array('links', 'inline', 'clearfix', 'main-menu')) to array('links', 'inline', 'clearfix', 'main-menu', 'new class')).

It actually looks like your referencing code sample from like this blog post from Koumbit:

> I added the following code to the template.php of my theme, to make both the standard user menu and our custom menu for anonymous users use Drupal's built in theming for inline links:

```
/**
 * Make the user menu inline
 */
function customtheme_menu_tree__user_menu($variables) {
  return '<ul class="links inline clearfix">' . $variables['tree'] . '</ul>';
}

```

But, I think what you really have to do is examine the theme's `region-menu.tpl.php` and see how it or like `page.tpl.php` is rendering the main menus, every theme is different.

Both `theme_links` and `theme_menu_tree` render *Sets* (collections) of links. Different themers use different functions to the same end.

Another module that can help you figure this out is Devel and Devel\_Themer. Toggle devel\_themer on and select your main menu and it will tell you the theme\_function being used and the .tpl file (and overrides possible) in use.

---
Tags: 7, routes, blocks
---


# Question
Title: How to rediret to specific page depends upon user roles
I have 2 user roles. When a user logs in, I want to redirect the user to a specific page based on their role. I tried the Login\_destination module, but it has not worked for me. I have also tried using the trigger action, but it has also not helped me. When I used this trigger action, the ajax module threw an unexpected error message.. SO please help me.. How do I solve this problem...

# Answer
> 0 votes
This is possible with rules You can try the following

1. Create a rule with event as "User has logged in".
2. Add condition "User has role(s)" and configure it as in screenshot
3. Then save the condition.
4. Now add action to you rule and select "page redirect" under system in the select the action to add dropdown.
5. This will open a form which will allow you to set the redirection path, simply in the value field give the internal page path you want the user to be redirected to and then save it.Check the screenshot for better understanding This way you can set redirect for one role and similarly you can create one more rule in a similar way for the other user role, if you want the other role to redirect to some other page.

---
Tags: ajax, users
---


# Question
Title: what does the 'debug mode' on Services actually do?
Each Services endpoint has an option for 'debug mode'.

What does this actually do?

# Answer
> 3 votes
The debug mode is essential to test if your service is working correctly through posting the logs. You can see the logs in admin/reports/dblog. These logs shows you if you are sending the appropiate format, if there is any error, etc. The logs allow you to see the output of the transactions. I have attached a image with some samples of the logs messages. As far as I understand that it is the only use for the debug mode in the services 3 modules. If it is not or this answer was not accquire please post a better explanation.

As you say it uses watchdog, so you can see internally what it is happening with your service. I have included the service code if you like to see the function yourself git service

---

.

---
Tags: services
---


title: Placeholders and the query builder?

text:
# Question
Title: Placeholders and the query builder?
I read on the drupal.org site: "Never put a literal value or variable directly into a query fragment, just as literals and variables should never be placed into a static query directly (they can lead to SQL injection vulnerabilities) http://drupal.org/node/1848348

```
$query = db_select('node', 'n');
$query -> condition('node', $nid);
$nodes = $query
-> fields('n', array('title'))
-> execute();

```

Does this also apply to queries written with the query builder, like the one above? If so, how should it be re-written?

Thanks

# Answer
To clear out the confusion, a `static query` usually refers to a raw mysql query that you use through `db_query()` function. You write the entire query and pass it as the first parameter of the `db_query` function.

Dynamic queries, like the one you have in your question, is called `dynamic query` which makes it really easy to build the query dynamically. Think about a query that you need to iterate through a dynamic list of conditions. You will need to fight with string related functions to build the query, that you can now use the query builder to do for you!

If you use something like this:

```
$result = db_query('SELECT n.title
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

```

It's considered safe against SQL injection (when you query the node table for users, always pay attention to their access permissions).

But this:

```
$result = db_query('SELECT n.title
FROM {node} n WHERE n.uid = ' . $uid);

```

**is bad**! We can't make sure that `$uid` will be completely safe to throw into the database.

> Does this also apply to queries written with the query builder, like the one above? With Query builder, you will not need to use these parameters (`:uid` from above "good" example) in most queries. `WHERE`, `ORDER BY` and other clauses have their own methods that you can use in the query builder. Your code in the question is in the correct format.

In case you need to use a variable in the query, **do** use parameterized pattern.

**Correct**:

```
$query = db_select('node', 'n');

$table_alias = $query->join('users', 'u', 'n.uid = u.uid AND u.uid = :uid', array(':uid' => 5));

```

**Wrong**:

```
$query = db_select('node', 'n');

$table_alias = $query->join('users', 'u', 'n.uid = u.uid AND u.uid = ' . $uid);

```

(I'm aware that above query couple do not make any sense :D Just copied from the linked page in your question)
> 4 votes

---
Tags: database
---


# Question
Title: How to get constant string array field into db_query?
First post here :)

Here's a valid MySQL query: `SELECT "'a','b'" AS FieldStrArray;`

(To enter as a string in PHP, remember the backslashes before double quotes.)

At least in Drupal 7's `db_query()`, this produces a fatal PDO exception, complaining that `'a','b'` is not a known field.

My question: how do I work around this apparent limitation of db\_query()/PDO?

(Yes, I need a constant string array as one of the field results. This is a minimal replication of the problem... :) )

Any suggestions MOST welcome... including a) whether this is also a problem in PHP itself, b) how to report this as a bug to the Appropriate Authorities, c) Any creative ideas for a workaround assuming it is a real bug.

Thanks!

# Answer
> 2 votes
Not sure if this is a bug or not (I've seen weird things with single and double quote in PDO queries before), but either way you can work around it by using single quotes to wrap the expression:

```
$sql = "SELECT '\'a\',\'b\'' AS FieldStrArray";
$val = db_query($sql)->fetchField();
// $val == "'a','b'"

```

---
Tags: 7, database
---


# Question
Title: Views 3 : Set header/footer/empty text for view via views_embed_view
I update my views from views 2 and I do the same on embedded code. But actually I can't set footer content as it changes in views 3.

My views 2 code :

```
$emptyTextVue = $view->display_handler->get_option('empty');
$emptyText = $view->display_handler->set_option('empty','<div class="ma-classe">Pas images.</div>');

```

I think I do use the export code like :

```
$handler->display->display_options['empty']['area']['content'] = 'Pas d\'images à afficher.';

```

but how ?

EDIT : extract result for var\_dump() : `["handler_type"]=> string(5) "empty" ["options"]=> array(11) { ["id"]=> string(4) "area" ["table"]=> string(5) "views" ["field"]=> string(4) "area" ["relationship"]=> string(4) "none" ["group_type"]=> string(5) "group" ["ui_name"]=> string(0) "" ["label"]=> string(13) "Zone de texte" ["empty"]=> int(0) ["content"]=> string(25) "Pas d'images à afficher." ["format"]=> string(1) "2" ["tokenize"]=> int(0) } ["definition"]=> array(4) { ["handler"]=> string(23) "views_handler_area_text" ["group"]=> string(6) "Global" ["title"]=> string(13) "Zone de texte" ["help"]=> string(33) "Provide markup text for the area." } ["is_handler"]=> bool(true) ["localization_keys"]=> array(4) { [0]=> string(7) "default" [1]=> string(5) "empty" [2]=> string(5) "views" [3]=> string(4) "area" } ["table"]=>`

# Answer
First up, don't use views\_embed\_view(). It is a very simple function that doesn't allow for customisation.

Do something like this:

```
// Load the view.
$view = views_get_view('VIEW_NAME');
// Set the options for the header text.
// To get an idea of what options are available, set up a view with header text
// and then use the devel module to print out the view definition.
// For example, add a header text area field and print it with
// dpm($view->header['area']); after you have loaded it with views_get_view().
$header_options = array(
  'label' => t('Header text'), // Administrative label. Not really needed here.
  'content' => 'This is the header text content.', // Content of header text.
  'format' => 'filtered_html', // Format of header text.
  'empty' => 1, // Show even when there are no results. Set to zero otherwise.
);
// This adds a header handler for a text area. The table is views because it is not
// a database field. The field is area because it is a text area.
// The header_options are the settings.
$view->add_item('DISPLAY_NAME', 'header', 'views', 'area', $header_options);
// This is the preferred way to get the rendered view.
$output = $view->preview('DISPLAY_NAME');
// If you want you can check for results with this.
if (!empty($view->result)) {
  // Do something if there are rows.
}

```

You can do the same for footer handlers:

```
$view->add_item('DISPLAY_NAME', 'footer', 'views', 'area', $footer_options);

```

and empty text:

```
$view->add_item('DISPLAY_NAME', 'empty', 'views', 'area', $empty_options);

```

You can also change the field type if you don't want to use Global: Text area.

For more information see $view-\>add\_item()
> 7 votes

# Answer
You can do something like the following. I'm using some Views hook functions to interact with a View object -- you probably want to review a blog post tutorial on some ways to embed views:

1. get a view
2. assign a display
3. add/remove filters
4. embed the view

After (2) above you have a `$view` object you can modify essentially as I do below. Another good resource (I think) on embedding views can be seen in the Embed Views contrib module documentation page.

I just happen to have this code around, the first function alters view Filters. The second function alters the default empty text.

Remember to edit the particular `$view[$display_id]` and its `$handlers` to see your changes at run-time.

```
/**
 * Implementation of hook_views_pre_view().
 *
 * Change the set filter to be the current Quarter/Year set in the CCS admin area.
 */
function courses_db_views_pre_view(&$view, &$display_id, &$args) {
  // This is /DEPT/courses
  #dpm($view);
  if ($view->name == 'departmental_courses') {
    $filter =& $view->filter;

    $fall_tid = 11;
    $year_2012_tid = 26;
    // We created these _tid variables so that we didn't have to look up the TID
    // on every page view by students.
    $q = variable_get('ccs_current_quarter_tid', $fall_tid);
    $y = variable_get('ccs_current_year_tid', $year_2012_tid);

  $view->display[$display_id]->handler->options['filters']['field_coursedb_quarter_tid']['value'] = $q;
  $view->display[$display_id]->handler->options['filters']['field_coursedb_year_tid']['value'] = $y;
  }
  if ($view->name == 'courses_for_instructor') {
    #dpm($view->display['block']->handler, 'handler');
    $quarter = variable_get('ccs_current_quarter', 'Fall');
    $year = variable_get('ccs_current_year', '2012');

    $view->display['block']->handler->options['title'] = t('@quarter @year Instructor of:', array('@quarter' => $quarter, '@year' => $year));
    $view->args[0] = $year;
    $view->args[1] = $quarter;
    #dpm($view->display['block']->handler, 'handler');
  }

}

/**
 * Implementation of hook_views_post_execute().
 *
 * For a view listing of migrated course data, show original legacy
 * data in the view header to allow auditing/verification of the
 * migrated data.
 */
function courses_db_views_post_execute(&$view) {
  if ($view->name == 'migration_audits') {  # Courses

    $drupal_nids = array();
    if (count($view->result)) {
      foreach ($view->result as $i => $node) {
        $drupal_nids []= $node->nid;
      }
    }

    $ccs_sql = <<<EOFSQL
SELECT mccd.*
FROM ccs_dump.mos_ccs_courses_db mccd
LEFT JOIN ccs_dump.migrate_map_csscourse mmc ON mmc.sourceid1 = mccd.id
WHERE mmc.destid1 IN (:drupal_nids)
EOFSQL;
    $result = db_query($ccs_sql, array(':drupal_nids' => $drupal_nids));
    $output = '';
    foreach ($result as $course) {
      #dpm($course);
      $title = html_entity_decode($course->course_title, ENT_COMPAT, 'UTF-8');
      $instructors = html_entity_decode($course->instructor, ENT_COMPAT, 'UTF-8');
      $output .= "<div class=\"entry\">$course->quarter $course->year - $title Instructors: $instructors</div>";
    }

    $ccs_values = "<style type=\"text/css\">div.legacy_values { background-color: pink;} div.legacy_values div.entry { padding-bottom: 5px; }</style><div class=\"legacy_values\">$output</div>";
    $view->display['page']->handler->handlers['header']['area_1']->options['content'] = $ccs_values;
    $view->display['page']->handler->handlers['header']['area_1']->options['empty'] = 0;
  }
}

```
> 3 votes

---
Tags: views
---


# Question
Title: How do I limit the number of images displayed in a teaser?
I have a site with an image field that allows for unlimited images. I want the first image in the field to be shown in the teaser (for both listing and views). Is there a configuration option that will let me do this?

I'd rather not put in a self-written module (as it means I have to maintain it myself).

# Answer
Try using this module http://drupal.org/project/field\_multiple\_limit

It allows you to go into the display settings for your content type and configure the teaser settings to display only a certain amount of values. You can even make it skip vales, for example if you want it to display values 2 to 5.
> 5 votes

---
Tags: 7, media, nodes
---


# Question
Title: Youtube Media with Media Module, won't render
I'm using the WYSIWYG module and I enabled the media browser button for it. When I add a youtube video, only the thumbnail shows... Why is this?! (I'm using ckeditor.)

# Answer
> 1 votes
The media module currently only has support for embedding images via WYSIWYG.

What version of media are you using? If you use media 7.x-2.x you can get it to work by using this sandbox module - http://drupal.org/sandbox/DevinCarlson/1823634 (note that you also need separate http://drupal.org/project/issues/file\_entity module with 2.x because it has now been split out of media - it was part of media in 7.x-1.x)

That sandbox module allows configuring which view modes are used for different file types when embedding via WYSIWYG.

There is a related issue for the media module here http://drupal.org/node/1792738 \- It has been decided in that issue that the sandbox module will be integrated into the media module. So you can safely use the sandbox knowing that the functionality will eventually be in the media module, at which point you won't need to rely on a sandbox project.

When using that setup of modules I find that in a lot of cases it is also good to use http://drupal.org/project/entity\_view\_mode \- which allows you to create new view modes (the file\_entity 7.x-2.x module doesn't provide many view modes out of the box).

---
Tags: media, files
---


title: Don't show latest content on frontpage

text:
# Question
Title: Don't show latest content on frontpage
How do I make it so Drupal doesn't automatically show latest content on frontpage?

# Answer
One way -- possibly the easiest way -- is to create a page containing whatever you want to be displayed on the home page, then going to `www.yoursite.com/?q=admin/config/system/site-information` if you're using Drupal 7 (or `www.yoursite.com/?q=admin/settings/site-information` if you're using Drupal 6), and then changing *Default front page* from `node` to `node/1` (assuming the page you created was normally located at `www.example.com/node/1`).
> 2 votes

# Answer
The best way depends on what you want on your home page.

If you want a page of content, then creating a node and setting it to the home page at admin/config/system/site-information is the best way.

However if you just want a page of blocks, with no node content, there are better ways. This is because creating a blank page and assigning it to the home page is a bit of a hack, and it means the system is wasting resources doing the node load and everything else that goes with it, for an empty node.

So instead you could use:

* Panels \- Add a panels page and assign blocks where you want them.
* Empty page \- Allows you to create empty pages, by assigning them a path and a page title. You can then assign blocks using drupal core blocks or using the context module.
* Front page \- Allows you to do a bunch of things, like set the home page content, or set the page to use for the front page. The only real reason to use this one is that is allows different front pages per role. So if for example you want a different home page for logged in users, use this module.

Then after you have one of those module set up, you can set the front page to your panels page/empty page at admin/config/system/site-information.
> 2 votes

---
Tags: nodes
---


title: Updating user profile to update node

text:
# Question
Title: Updating user profile to update node
I currently have a user's profile set up with some extra fields and when that user obtains the role "paid user" an entity is created with a rule and a node that copies those extra fields in the profile is then published. I'm having an issue however, that whenever I update the user's profile fields, it creates ANOTHER node and leaves the old one.

I'm looking for a solution that will either delete the duplicate node OR will update the current one.

Does anyone have any ideas for this? I've tried the deduped module someone built for Drupal 7 but it doesn't seem to be working.

EDIT: Here is the second Rule I've created to try to unpublish the older node.

```
Event: Before saving a user account
Conditions: Entity exists by property(Entity type: Node, Property: Title, Value: [account:field-business-profile])

Data comparison(Parameter: Data to compare:[account:field-bus-name],Data value:[account:field-business-profile:title])

Actions: Unpublish content(Parameter:Content:[account:field-business-profile])

```

EDIT2: I've updated the second rule to rooby's edits. The original content remains published though. I've tried going back and forth between the account-business-profile:nid and account-unchanged-business-profile:nid to no avail. Here are some pictures I've uploaded of the rule and the two pieces of content:

# Answer
Moving to an answer so I don't overload your question with comments.

Your second rules doesn't seem to ever load the node you want to unpublish/edit.

You need an action for "Fetch entity by property" (although I would be wary of fetching by title, I prefer the safety of node ID). For this action you can limit it to 1, so it only gets one node (there should only be 1 anyway).

Then that will fetch your node, and then you can do comparisons on that node or unpublish that node (or whatever else you may want).

The problem is though is that at this stage rules only knows it is an entity, it doesn't know what type or anything so you can't actually access its fields or do node actions like unpublish on it.

So (I think this is the only way) you have to install the http://drupal.org/project/rules\_conditional module.

Then after your "Fetch entity by property" action you can add a loop and loop over entity-fetched (it will return an array even though you specified to return 1.

Then in this loop add a "Conditional".

Then in the conditional add an "If". For the if you can do entity has field, or entity is of type and content is of type. You can add multiple Ifs. If you want multiple nested ifs you have to add it like conditional if entity is of type node conditional if content is of type page action unpublish node

Once you have added the ifs rules will know that the fetched-entity is a node and what fields it has.

Then you can add an unpublish action and select entity-fetched (or list-item because of the loop)

So your rule might look like this:

```
Event: Before saving a user account
Action: Fetch entity by property(Parameter: Entity type: Node, Property: Title, Value: [account:field-business-profile], Limit result count: 1 Provides variables: Fetched entity (entity_fetched))
Action Loop: (Property: List: [entity-fetched], List item: Current list item (list_item))
  Conditional:
    If: Entity is of type (Parameter: Entity: [list-item], Entity type: Node)
      Conditional:
        If: Content is of type (Parameter: Content: [list-item], Content types: Basic page)
          Action: Unpublish content (Parameter: Content: [list-item])

```

Or it could look like this (without the loop, just working on the 1st entity-fetched):

```
Event: Before saving a user account
Action: Fetch entity by property(Parameter: Entity type: Node, Property: Title, Value: [account:field-business-profile], Limit result count: 1 Provides variables: Fetched entity (entity_fetched))
Conditional:
  If: Entity is of type (Parameter: Entity: [entity-fetched:0], Entity type: Node)
    Conditional:
      If: Content is of type (Parameter: Content: [entity-fetched:0], Content types: Basic page)
        Action: Unpublish content (Parameter: Content: [entity-fetched:0])

```
> 5 votes

# Answer
One approach I've used on a site in the past is to create the entity on profile creation and link it with a relation (I used the Relation module because at the time I couldn't get the rules integration of Entity Reference working).

I then used permissions (with the Revisioning module because I also needed to approve changes) to limit access to editing that profile to users with the appropriate role.

Then, when the user becomes a paid user, I simply have a rule that publishes the node by calling it through the relation, and another rule that unpublishes the node.

This approach creates one extra node in the database per user; some people may not like this but for me it was a good tradeoff for simplicity's sake.

To copy the values of the fields, since the nodes will already be created and you don't have to worry about saving the node first, you can just add an action set component to the rule that is a sequence of *Set data value* actions.
> 2 votes

---
Tags: rules, users, nodes
---


# Question
Title: Theme the login page for Maintenance mode
I've created my theme as subtheme of ZEN, and I have created my maintenance page template, which works when I enable the maintenance page.

If I try to visit example.com/user, the *login* page is shown with the standard template, and not with the maintenance-page template.

How do I make Drupal 7 use the maintenance page template also for the login page?

# Answer
> 1 votes
If you want the login page to look different when you are in maintenance mode you theme it by checking the maintenance mode variable like this:

```
if (variable_get('maintenance_mode', 0)) {
  // Do something because it is maintenance mode.
}

```

For example, in your page template you could do this:

```
/**
 * Preprocess variables for the page template.
 */
function THEME_NAME_preprocess_page(&$variables) {
  if (variable_get('maintenance_mode', 0)) {
    // Add a template suggestion for pages that are not the maintenance
    // page, while the site is in maintenance mode.
    $variables['theme_hook_suggestion'][] = 'page__inmaintenancemode';
  }
}

```

Then you could make a page--inmaintenancemode.tpl.php file, that could be used to theme any pages that are visible while in maintenance mode. Be aware though that this will then affect all pages you see when you are logged in during maintenance mode, so you might want to change the line that check for maintenance mode to:

```
if (variable_get('maintenance_mode', 0) && user_is_logged_in()) {

```

You can do the same check in hook\_form\_alter() or in other template preprocessors, or anywhere else you are modifying content.

# Answer
> 0 votes
I take it this is a temporary patch while you're developing the site, right? You could trick Drupal into using the maintenance page in place of the user-login.tpl.php by setting up a symbolic alias from the command line, ex:

```
ln -s maintenance-page.tpl.php user-login.tpl.php

```

Of course if you currently have a user-login.tpl.php file in your theme you're going to want to move it to a backup version first, ex:

```
mv user-login.tpl.php user-login.bak.tpl.php

```

Then when you're ready to make the switch back, just remove the symbolic link and mv the file back:

```
rm user-login.tpl.php
mv user-login-bak.tpl.php user-login.tpl.php

```

---
Tags: theming, maintenance-mode
---


# Question
Title: How add related nodes to content profile?
In Drupal 6, I am trying to list the links to nodes created by that user and/or nodes which have her name in their tags below the profile. But I could not figure out how to do either. I appreciate your help.

# Answer
> 0 votes
You can load nodes by various parameters. Just give the parameters which you want to load. See here Here is for Drupal 6 also.

If you had a code in D6 to load a node using an array of conditions to match against in the database query like this:

```
<?php
$param = array(
    'type' => 'your_node_type',
    'title' => 'your node title',
    'status' => 1,
);
$node = node_load($param);
?>

```

# Answer
> 0 votes
To list content owned by a user you should ...

1. create a View that lists content
2. create a Relationship in that view to the User that owns that content
3. create a Block Display within that view
4. configure an "Argument" for that view which "Provides Default" and grabs the UID of the User from the URL
5. place that block using some mechanism for Block placement on each User Page.

hope that general recipe helps.

---
Tags: nodes, 6
---


title: Upload a file to a subfolder

text:
# Question
Title: Upload a file to a subfolder
I'm working on a feature that will allow me to create series of nodes. Each node will have a number of associated files. I'd like to be able to upload the files to a directory that uses some fields from the parent node. In other words, when the file is uploaded, a directory is used (or created if it doesn't exist yet) that uses the date the node was created and the title of the node. I know I can specify a static directory to use when creating a file field, but I need create a subdirectory inside the parent directory. Is this possible?

# Answer
You can set the upload directory on the field settings for file fields.

By default the available tokens that can be used to create the directory are not that useful, because you can't use tokens for the node you just saved, for example.

To do that you can use the http://drupal.org/project/filefield\_paths module.

It will allow you a much wider range of tokens. It also allows you to use tokens in the file name, as well as the directory.
> 2 votes

# Answer
If you look under your filefield settings you will see a field that called, “File directory” that is self-described as:

> Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes. This field supports tokens.

You can use tokens. Something like. `[current-date:short]/[current-page:title]`
> 3 votes

---
Tags: files
---


title: Remove link to user profile on content

text:
# Question
Title: Remove link to user profile on content
How do I remove the link to a user's profile on article content? The element is part of the article header and its classname is ".username". I am new to Drupal but not to webdesign; I am just having trouble pinpointing which file to edit.

I tried:

```
function phptemplate_links($links, $attributes = array()) {
    unset($links['.username']);
    return theme_links($links, $attributes);
}

```

in my theme template.php file but it did not work.

Just to be clear: I am trying to remove the element but not the text. I still want the user's name to appear, just not the link to the profile page. Also, I am looking for a PHP-based solution, not CSS, and trying to avoid adding any more modules.

Thanks!

# Answer
> 1 votes
You can't do this with CSS but you can do it without having to add another module.

If you want it exactly the same as default, but without the link, this would be it:

Just add this code to your template.php file in your theme (change YOURTHEME to be your theme name):

```
/**
 * Override or insert variables into the node template.
 */
function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->type == 'article') {
    // This will replace the user name link with the same text but without the
    // link.

    // Set the name to a formatted name that is safe for printing and
    // that won't break tables by being too long. Keep an unshortened,
    // unsanitized version, in case other preprocess functions want to implement
    // their own shortening logic or add markup. If they do so, they must ensure
    // that $variables['name'] is safe for printing.
    $name = format_username($node);
    if (drupal_strlen($name) > 20) {
      $name = drupal_substr($name, 0, 15) . '...';
    }
    $variables['name'] = $name;
    // Display post information only on certain node types.
    if (variable_get('node_submitted_' . $node->type, TRUE)) {
      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    }
  }
}

```

if YOURTHEME\_preprocess\_node() already exists in your theme just add this to it:

```
  $node = $variables['node'];

  if ($node->type == 'article') {
    // This will replace the user name link with the same text but without the
    // link.

    // Set the name to a formatted name that is safe for printing and
    // that won't break tables by being too long. Keep an unshortened,
    // unsanitized version, in case other preprocess functions want to implement
    // their own shortening logic or add markup. If they do so, they must ensure
    // that $variables['name'] is safe for printing.
    $name = format_username($node);
    if (drupal_strlen($name) > 20) {
      $name = drupal_substr($name, 0, 15) . '...';
    }
    $variables['name'] = $name;
    // Display post information only on certain node types.
    if (variable_get('node_submitted_' . $node->type, TRUE)) {
      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    }
  }

```

# Answer
> 1 votes
You can create node--\[content-type\].tpl.php for your node and can display the username by $node variable and comment the default $submitted variable.

---
Tags: theming, users
---


# Question
Title: How can I display the content of user profile using the Views module?
I want to create a view for displaying the title of the content posted by the user whose profile is being currently shown using the Views module. I am using the following modules:

* Views for displaying the profile related content
* Panels: for displaying the user profile

How can I do this?

# Answer
> 1 votes
Wow what a coincidence this question was posted for drupal 6 just this morning.

To list content owned by a user you can:

1. Create a View that lists content
2. Create a Block Display within that view
3. Configure a "Contextual filter" for "Content: Author UID" and set its "When the filter value is NOT in the URL" setting to "Provide a default value", then select "User ID from URL" for the "Type".
4. Place that block on the user profile page using some mechanism for Block placement, like the drupal core block system or the context or panels modules.

---
Tags: 7, views
---


title: Contextual Filters with PHP code

text:
# Question
Title: Contextual Filters with PHP code
I am setting up a contextual filter for several taxonomy fields on a content type that stores my organizations records. I want to present my users with a nice looking url, not the TID. For the contextual filter, I have selected Provide a Default Value and selected Use PHP Code. This is the code:

```
$term_name = "Open";
$termObj = taxonomy_get_term_by_name($term_name);
$term = reset($termObj);
return $term->tid;

```

For now, I'm hard coding the term until I can get it working, then I'll switch it to a term out of the URL. When I save the contextual filter, the preview shows "No query was run". After I save the view and visit the page created by the view, Drupal gives me a Page Not Found message.

# Answer
As I am always against adding PHP code in the UI may I suggest a different approach?

Add a relationship to your view "Content: age group", which is the relationship from your term reference field to the taxonomy term.

Then add a contextual filter "Taxonomy term: Name", using the relationship you just added.

Then the argument will be the term name without you having to add custom PHP code.
> 3 votes

---
Tags: views
---


# Question
Title: What is the reason behind the current menu structuring
I'm not much of a Drupal Ninja; from what I saw at http://drupal.org/node/788972,
Drupal seems to have a menu structure like Joomla, in the sense that it allows menu items to be created under menu categories. Why are we using this unlike a central menu items section, from which we can link an item to multiple menus, if needed?

This is what I can see in Wordpress. In the latter method, I can see reduced redundancy and a single point to change multiple occurrences of the same link.

I would like to understand the logic/reasoning behind the Drupal menu structuring, not understanding how Drupal compares to Joomla or WordPress.

# Answer
> 2 votes
You can create as many menu items as you want and have them point wherever you want. You can do this in code and in the UI.

Drupal menus have plenty of flexibility, especially with contrib.

More:

You can set up many different menus (and not just one overall hierarchy) because that way you can have more than one menu. You can put them wherever you want on the page. You can have a sidebar menu and a top-strip menu and whatever else.

Internally, the menu system is really a routing system. Drupal uses the same set of code for routing requests as it does for presenting menus in web pages. Each route/item can have its own permissions, so the list of items the user sees is determined by their role, automatically.

In short, to recap: The reasoning behind Drupal menu structuring is that it's flexible.

# Answer
> 1 votes
The way you see this working is purely the way the menu UI has been written. The way menus are structured in the database allows for all sorts of other possibilities, which anyone could make a module to do.

I assume (I don't know because I was not involved with the building of the menu module and I have not ever investigated this):

The reason is that in drupal the menu UI centres around menus, not menu items.

This is because you generally have one or more menus that you want to display around the site, so you add menu items to a given menu.

The alternative is that everything revolves around menu items (paths) and you go to a path and say "I want this path to be in all these menus".

I would say the decision was made (if it was even a decision. It is quite possible it was just written this way and no one questioned it) based on perceived use cases.

Personally, I can see more use cases for managing menus at the menu level than at the menu item level. Rarely would I ever want to see all menus that a menu item is in. Usually I just want to manage a menu, then put it where it has to go in the layout. It is a discrete menu, so it is managed that way.

I can see there would be some use cases for seeing all menu items for a given page, but I definitely think it is less common than wanting to see what menu items are in a menu.

Views has menu item support so it is very easy to create a menu item view that would present the alternative UI.

---
Tags: routes, navigation
---


# Question
Title: Drupal7 user reset password link not working
Hi i have created a custom hook in my own themeplate

```
function mytheme_theme() {
  $items = array();

  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-reset',
    'preprocess functions' => array(
      'mytheme_preprocess_user_pass'
    ),
  );
  return $items;
}

function mytheme_preprocess_user_pass(&$vars) {
  $vars['intro_text'] = t('This is my super awesome reg form');
}

```

This is the code in user-reset.tpl.php

```
<p><?php print render($intro_text); ?></p>
<div class="yourtheme-user-login-form-wrapper">
  <?php print drupal_render_children($form) ?>
</div>

```

after the user register. an activation link will send to the user email
example: http://www.mysite.com/user/reset/98/1366527945/qr6sEqrJwpWjQ11sxQPpitIHosg3\_-Iv1s08yrKlnYk

Problem is:

When user trying to click the link, the page give me an error "The page isn't redirecting properly"

is there anything i missed on my own theme?

cherrs

# Answer
> 1 votes
Not sure exactly what is wrong with your code (I will check it out in a min), but if the purpose is just to add some text to the password reset form, I would do it in one of these ways:

1. Add a custom block with the text you want to add and assign it to the user register page.
2. Add a custom module and use hook\_form\_alter to add custom markup. Like so:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_user_pass_alter(&$form, &$form_state) {
  $form['intro_text'] = array(
    '#markup' => '<p class="intro-text">' . t('This is my super awesome reg form') . '</p>',
    '#weight' => -10,
  );
}

```

---
Tags: theming
---


# Question
Title: Using multiple taxonomy vocabularies for views filters
I need to display nodes in a view, based on a combination of multiple taxonomy terms, in multiple vocabularies. For example, for car sales, one vocabulary lets the visitor select one or more colors, and another selects one or more model types.

I assume I can do this by exposing filters, but how do I group them as check boxes in a sidebar instead of on top of the view?

# Answer
In the "Advanced" section of your view settings, select Yes for the "Exposed form in block" setting.

Then there will be a block available for your view, which you can assign using drupal core blocks, context, panels, etc.
> 2 votes

---
Tags: 7, views
---


title: Entity Reference with VBO and Rules

text:
# Question
Title: Entity Reference with VBO and Rules
I am trying to create a rule which fires after modifying node content. Specifically I want to modify the entity reference field values of all the node entities provided by VBO. So I created a rule and a component as shown in the images below. My problem is that I can not find a way to empty the entityref list of all node entities before the loop, maybe my whole approach is wrong.

# Answer
I'm not sure what the Change combine with field action does but if you want to set the value of an entity reference field can't you just use the "Set a data value" action in your product\_display loop for the entity reference field?
> 2 votes

---
Tags: rules, entities, views
---


title: how to edit the link user/%/edit?

text:
# Question
Title: how to edit the link user/%/edit?
i have a test user called "buyer". he has a profil with the tabs: view - edit - orders - files i set pathauto for user to: user/\[user:name\] when i look at the tab links the as followed:

view: domain/user/buyer edit: domain/user/82/edit

question: why is that? if i call the link domain/user/buyer/edit by hand, i get "You are not authorized to access this page."

any ideas?

# Answer
It is because path aliases are for a single path, so the path alias user/\[user:name\] is only for user/82. If you want path aliases for all those other pages, they have to be added separately.

And because they are not pages that are covered by the pathauto module, you cannot use it for those pages.

You can manually add aliases at admin/config/search/path/add but because you can't use tokens there you would have to add aliases manually for each user (which is ridiculous).

The only module I know that can help you out is http://drupal.org/project/subpathauto

The equivalent module for drupal 6 is http://drupal.org/project/subpath\_alias

Those modules aim to allow you to do what you desire.

It seems there is currently a bug in the subpathauto module though that is breaking user aliases. See http://drupal.org/node/1851102

I just tested 7.x-1.2 and it is working correctly.

You can get 1.2 from here - http://drupal.org/node/1416736
> 1 votes

---
Tags: users, path-aliases, routes
---


# Question
Title: Show a page with child Terms when parent Term clicked in block?
I want to Display child terms when a parent Term is clicked with Views in Drupal 7. Example

```
     Parent1
          .child11
          .child12

      Parent2
          .child21
          .child22
          .child23

```

So when Parent1 page is Visited, i will display the content of parent1 but with a block showing

```
          .child11
          .child12

```

Any insight in Achieving this will be Appreciated. Thank you.

# Answer
Try the Views tree module. It is great for taxonomy trees.

> This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
>
> It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.

There is also a patch for adding collapsible support but I'm not sure how complete it is. See http://drupal.org/node/1538414
> 1 votes

# Answer
Download and install the Taxonomy menu module, it will exactly match your requirement. More details from the module's project page:

> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules

See the demo http://taxonomymenu.davidstoline.com/ (click the terms and you can see the term highlighted in the block)

Hope it will help you!
> 0 votes

---
Tags: views
---


# Question
Title: Easy way to make an Installation Profile
I want to use my current website as an installation profile. I've set it up so it contains some useful content types, views and example content nodes. Is there a no-coding way to create an installation profile that would look exactly as my current site when installed?

# Answer
> 2 votes
AFAIK, there's no one module that does all that **perfectly**. But depending on what your site is made of, there are a few modules that can come pretty close. Profiler Builder is probably the closest thing to what your looking for.

> It builds the .info, .profile, .install, .make, and .make.example files necessary to turn a site into a distribution / installation profile and tar's them up as a download.

The Features module can also be very useful as it allows you to package together subsets of functionalities (e.g. modules and settings for an image gallery).

---
Tags: users, distributions, backups
---