# Question
Title: Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column
I'm trying to migrate user's content profiles (Drupal 6) to Profile2's profiles (Drupal 7) using the example from http://grasmash.com/article/migrate-classes-content-profile-profile2. When I try importing, I get the following error:

> Migration failed with source plugin exception: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'ctp.field\_titul\_pred\_jmenem' in 'field list'

This is the migration class.

```
class SkipProfile2Migration extends Migration {
  public function __construct() {
    parent::__construct();
    $this->description = t('Migration of content profile into profile2 entities');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'nid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'D6 Unique Node ID',
          'alias' => 'n',
        )
      ),
      MigrateDestinationNode::getKeySchema(),
        'default'
    );
    $query = Database::getConnection('default', 'legacy')
      ->select('node', 'n')
      ->fields('n', array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'moderate', 'sticky', 'tnid', 'translate'))
      ->condition('n.type', 'profile', '=');
    $query->join('skip' . '.node_revisions', 'nr', 'n.vid = nr.vid');
    $query->addField('nr', 'body');
    $query->addField('nr', 'teaser');
    $query->addField('nr', 'format');
    $query->join('skip' . '.users', 'u', 'n.uid = u.uid');
    $query->addField('u', 'name');
    $query->leftJoin('skip' . '.content_type_clovek', 'ctp', 'n.nid = ctp.nid AND n.vid = ctp.vid');
    $query->addField('ctp','field_titul_pred_jmenem');
    $query->addField('ctp','field_krestni_jmeno');
    $query->addField('ctp','field_prijmeni');
    $query->addField('ctp','field_titul_za_jmenem');
    $query->addField('ctp','field_telefon');
    $query->addField('ctp','field_email_source');
    $query->addField('ctp','field_ulice');
    $query->addField('ctp','field_cislo_popisne');
    $query->addField('ctp','field_sidlo');
    $query->addField('ctp','field_smerovaci_cislo');
    $query->addField('ctp','field_funkce_cloveka');
    $query->addField('ctp','field_pracoviste');
    $query->addField('ctp','field_stat_iso');
    $query->orderBy('n.nid', 'ASC');

    $source_fields = array(
      'nid' => t('The node ID of the page'),
      'uid' => t('The user ID of a user'),
      'lid' => t('The location ID of a location instance'),
    );

    // Create a MigrateSource object, which manages retrieving the input data.
    $this->source = new MigrateSourceSQL($query, $source_fields);
    $this->destination = new MigrateDestinationProfile2('clovek');

// FIELD MAPPINGS    ...

```

Can anybody help me, please?

# Answer
On Drupal 6 running CCK, the database field names are different from the CCK field names.

In my test site running Drupal 6, I created the following CCK fields:

* field\_code\_page (text)
* field\_co\_author (user reference)
* field\_book\_list (node reference)

The database table created from CCK for the content type containing those fields has the following database fields:

* field\_code\_page\_value
* field\_co\_author\_uid
* field\_book\_list\_nid

It is rather probable the database field is named ctp.field\_titul\_pred\_jmenem\_value. To be sure, you should check the database table, as the database field could have a different name, basing on the type of the CCK field.
> 1 votes

---
Tags: 7, migrations
---


title: Hook that runs after template.php

text:
# Question
Title: Hook that runs after template.php
Currently, I am using `hook_page_alter()` in my module, but this runs too early. I am loading some fields from the node in template.php so that I can put them into other regions. These fields need JavaScript code from my module, after they are loaded, as the JavaScript depends on the IDs which are generated during the field loading process.

If anyone can help or point me to a list of hooks ordered by the point at which they are run then that would be a great help.

# Answer
> 2 votes
template\_preprocess\_field() hook is your friend.

The general flow is:

theme($hook, $var) \>\> preprocess functions \>\> process functions \>\> finally either goto template.php or call theme function \>\> return output as string

therefore, template.php or theme function call is the final destination, no hook runs after template.php

---
Tags: 7, hooks, theming
---


# Question
Title: Pasting into CKEditor creates divs instead of paragraphs
I'm working with content owners who think it's a good idea to compose their content in Microsoft Word. Although I've created a detailed guide for them on how to make this less painful (describing how to format things in *meaningful* ways in Word, like using header styles instead of just bolding your text to make it look like a header--things that are obvious to anyone who cares about semantic HTML, and that should be obvious to a user of Word who actually cares about quality and precision instead of just spewing words all over the page), they pretty much ignore it and create poorly formatted content, which of course means it just gets worse when copied and pasted into a rich text editor in Drupal.

Since they don't know HTML, and so can't easily fix this horrible formatting in the rich text editor, I've suggested copying it into a text editor (probably Notepad for them) and then pasting it in, and adding the formatting again in the rich text editor.

The problem I'm running into here is that the WYSIWYG module, or else CKEditor itself, creates elements for each paragraph instead of

elements. I'm not sure why this is, but it is of course a very bad thing from the points of view of semantic HTML, CSS styling, and any other point of view I can think of.

How can I fix this? How can I set things up so that plain text which is pasted into the WYSIWYG editor will give me

elements for each paragraph instead of elements?

# Answer
> 4 votes
I believe this problem is unique to the Chrome browser, i.e. when pasting text directly into the WYSIWYG you get divs instead of paragraphs. In Firefox, for instance, you get paragraphs instead.

One workaround is to use the "Paste as plain text" or "Paste from Word" buttons. This should give you paragraphs instead of div tags.

You could also click the "Source" button and paste the text, then when clicking "Source" again the text should be converted into HTML with paragraphs.

---
Tags: wysiwyg
---


# Question
Title: How do I show multiple nodes on the same page without writing code?
Let's say on my "contact" page, I want to use a google map (module), contact form (webform module), show our address (node using Address field), and list some social icons. Let's say stacked on top of each other in the "content" region.

What is the easiest way to do that?

Note: this similar question involves code, I want to avoid that:

How do I create multiple nodes on the same page?

# Answer
I came to a similar situation of your question before. I need a page, divided to two parts. On left shows company info such as Google map, company address, phone number etc. On the right side, shows a "Webform-ed" Contact Us form. The single page is actually a Panel node of a combination of two other nodes.

My solution is use Panel modules.

Enable modules:

Create a Panel Node, pick a layout of the Panel node.

Add content to each place.

Select existing node you created. (e.g Company info node & Contact us node)
> 2 votes

# Answer
use the display suite module and make blocks for each item. put the blocks into a custom view mode. you could also use like either entity\_view\_modes or view\_mode\_page to create the custom 'view modes' for your content.

In general, its neat to be able to do all this with an administrative UI (Views UI, DS interface, Field UI view modes); but all of these modules can have a steep learning curve by themselves -- let alone working together. Also, these are not small modules depending on your host environment.

Doing a custom page with `hook_page_build` or `hook_page_alter` and making blocks in code or with the views\_ui can be much leaner.

To each his own.
> 1 votes

# Answer
Use Entity Reference module at http://drupal.org/project/entityreference .

Create a new content type called "Contact Page" or whatever you want to call it. Add a field called "Embedded Nodes" of type Entity Reference with the autocomplete widget. In the field configuration, designate which nodes the field can reference in target bundles and set number of values to unlimited. After save, go to manage display and for the format of the "Embedded Nodes" field, choose "Rendered Entity". You can also choose which view mode to use - Full Content is fine. So now when you create a content type, you can reference other nodes to be displayed within the node. You can embed and re-order nodes at will without views.
> 1 votes

---
Tags: 7
---


# Question
Title: How to enable user search in Apache Solr?
I have Apache Solr running on my site, but would like to get it to index users as well as nodes, so that a single search request will bring up matching users as well as nodes. What do I need to do to make this possible? I found some pages talking about installing the Content Profile module to create nodes corresponding to users, which solr could then presumably find, but Content Profile doesn't seem to have made the jump to Drupal 7. Is something like this required, or will Solr just do this once I tweak some configuration step that I apparently missed?

# Answer
> 5 votes
There is the Apachesolr User module, which has just a development snapshot release for both Drupal 6, and Drupal 7. It is used from 76 sites, 72 of which run Drupal 7.

Basing on the module description, it could suit for you.

> This module will add users to apache solr. It is compatible with the latest beta of Apache Solr search integration. It now exposes the User entity type as an indexable entity type so it can be indexed properly. All Apache Solr hooks are available to modify the way you are indexing users.

Looking at the issue queue for the module, I found Only users with the "Bypass content access control" permission are able to search for users when Apache Solr Access is enabled. Before using the module I would rather wait that issue is fixed. If you aren't using the ApacheSolr Access module, you should not have the issue reported there. That is what a user commented.

---
Tags: search
---


# Question
Title: String Field as Link to Content (replacing node title field)
I dislike the fact that the Node Title is not truly a field because it prevents me from being able to control its display order, etc., like I can with all of the other fields. I tried using the `exclude_node_title` module which did as it claimed and I added a new field called Post Title of type Text.

How can I make that new custom title field into a link to the Content?

# Answer
If you are a *Drupal module developer*, the easiest way to do this would be to define a custom field formatter that would specifically do this (i.e. linking field value to the URL of the node) for the text field and content type that you want.

If you are looking for a *UI solution*, I'd suggest installing the `custom_formatters` module. Once you have done that, import the formatter below.

```
$formatter = new stdClass();
$formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
$formatter->api_version = 2;
$formatter->name = 'string_to_link';
$formatter->label = 'string_to_link';
$formatter->description = 'Converts string from a text field attached to a node to a link';
$formatter->mode = 'token';
$formatter->field_types = 'text';
$formatter->code = '<a href="[node:url]">[node:title]</a>';
$formatter->fapi = '';

```

Now, go to the "Manage Display" page of the content type where you have your Node title field, and set the formatter to \*Custom: (string\_to\_link)\*. The value of the field is immaterial now. It'll be linked to the node always.

However, linking to the node from the node view itself is not really of much use, right? So, I'm guessing you'd want this in a node listing. (A set of nodes). In that case, you might want to use the `Views` module where you can explicitly link the node title to its URL for a view.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Users that can add other users in drupal 7
Scenario is as follows: admin adds users (coordinators). Coordinators should be able to add another type of users (editors) which can create content. What is the best solution to this scenario? I don't want any of the users assign roles to other users. Coordinator should be able to add only one, defined type of user.

# Answer
> 1 votes
There's a module for that: Administer Users by Role.

> This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.
>
> To use this module:
>
> 1. Create a role for the users who you'd like to be able to create/edit/delete other users
> 2. Give that new role the 'administer users' permission and give it the desired *Administer Users by Role* permissions

I'm using it exactly for the same purpose you described.

---
Tags: 7, users
---


# Question
Title: Control display of post date as standard field?
Like many who came before me... I have a problem with the way drupal 7 allows me to control the display of the post datetime of a node.

I would like to be able to control the display of the post date as a standard field so that I can just simply order it within my fields. I know that I can edit the node.tpl.php but that's not what I'm trying to do. I want it rendered within the content fields.

Is there a module that will create a virtual field that mimics the post date or something like that?

Or is there a module that provides a date time which will automatically set itself to "now" when a new node is created?

# Answer
> 1 votes
display suite creates a "virtual" field for the post date and also for other properties of the node (submitted by, author,..). You can also set a date format for the post date.

To use it, enable ds and ds\_ui, go to Manage display of a content type and choose a layout. You will see the mentioned fields.

---
Tags: 7, datetime
---


# Question
Title: debug_backtrace and _drupal_error_handler_real with very high mem usage, can I disable?
I was profiling some of my code with xhprof, and I noticed that `debug_backtrace()` and `_drupal_error_handler_real()` have a very high memory usage.

I set "Error message display" to "None" at admin/config/development/logging, and I also have database logging module disabled. Still, these functions seem to collect error information. Do you have any idea why it happens?

My code does generate some PHP warnings. If I fix them, would these error calls disappear?

# Answer
\_drupal\_error\_handler\_real() is the function called from the error handler installed from Drupal (\_drupal\_error\_handler()). A PHP error handler is called every time there is a not-handled runtime error (not an exception), including a warning.

The code execute from `_drupal_error_handler_real()` is the following one. debug\_backtrace() is always called, if the error level is one set in PHP.

```
  if ($error_level & error_reporting()) {
    $types = drupal_error_levels();
    list($severity_msg, $severity_level) = $types[$error_level];
    $caller = _drupal_get_last_caller(debug_backtrace());

    if (!function_exists('filter_xss_admin')) {
      require_once DRUPAL_ROOT . '/includes/common.inc';
    }

    // We treat recoverable errors as fatal.
    _drupal_log_error(array(
      '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
      // The standard PHP error handler considers that the error messages
      // are HTML. We mimick this behavior here.
      '!message' => filter_xss_admin($message),
      '%function' => $caller['function'],
      '%file' => $caller['file'],
      '%line' => $caller['line'],
      'severity_level' => $severity_level,
    ), $error_level == E_RECOVERABLE_ERROR);
  }

```

Also \_drupal\_log\_error() is called when `debug_backtrace()` is called, but without any module recording the error, the error is not effectively recorded. In fact, the error is recorded if there are modules implementing hook\_watchdog(), such as the Database logging module, and the Syslog module. The task of watchdog(), the function called by `_drupal_log_error()` is pass the information about the error to the implementations of `hook_watchdog()` which are then free to record the error.

```
// Prepare the fields to be logged
$log_entry = array(
  'type' => $type,
  'message' => $message,
  'variables' => $variables,
  'severity' => $severity,
  'link' => $link,
  'user' => $user,
  'uid' => $user_uid,
  'request_uri' => $base_root . request_uri(),
  'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
  'ip' => ip_address(),
  // Request time isn't accurate for long processes, use time() instead.
  'timestamp' => time(),
);

// Call the logging hooks to log/process the message
foreach (module_implements('watchdog') as $module) {
  module_invoke($module, 'watchdog', $log_entry);
}

```
> 2 votes

---
Tags: debugging
---


# Question
Title: Why are only a few actions available on my triggers page?
I'm customising the content publishing flow of my site using actions and triggers. Unfortunately I've got a problem that not all the actions are show on the triggers page.

For example on I have: \["Choose an action", "Make content sticky", "Make content unsticky", "Promote content to front page", "Publish content", "Remove content from front page", "Unpublish content", "Change workflow state of post to next state", "Ban IP address of current user", "Block current user"\]

Whereas on all other trigggers I only have these actions available: \["Choose an action", "Delete archived revisions", "Publish the most recent pending revision", "Change workflow state of post to next state", "Ban IP address of current user", "Block current user"\]

Does anyone know why all actions are not shown for all available triggers?

Thanks

# Answer
> 1 votes
I had the same problem. The solution is to use the RULES module which is the successor of Triggers. If you want to use Triggers anyway (you shouldn't as my impression is it is being phased out and migrated to RULES) you would have to do code modifications (via drupal hooks).

With Rules, you can have all these options about publication of nodes and even more.

---
Tags: actions, rules
---


title: Drupal 7 Add Readmore to Basic Page

text:
# Question
Title: Drupal 7 Add Readmore to Basic Page
I am new to Drupal, I have requirement to add a readmore link to Basic Page content. That readmore trim the full content.

# Answer
There are a few 'read more' link modules, like this one: http://drupal.org/project/read\_more

There is also the 'teaser' display mode, as on the front page.
> 1 votes

# Answer
You can use display suite to control how to use the read more. You can trim your text field and then show the read-more. The read more will link to the full content.With Display suite you can also change the label of the read more with Display suite. I like this article detailing what you can do with Display Suite:
> 0 votes

---
Tags: theming
---


# Question
Title: Display Location of node Title different in Teaser vs Full
I created a custom template, `node--article.tpl.php` which renders my `field_image` field first, then shows the submission date, then displays the title and then renders the rest of the content.

This works very well in Teaser, but when I click on the node and view it in Full, the Title is rendered at the top. It is above the `field_image` instead of where it exists in the template. My template is just a slightly altered version of the Zen `node.tpl.php`. Why is the title being rendered up top instead of where it is in the template?

Here is my template:

```
<article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($content['field_image']); ?>

  <?php if ($display_submitted): ?>
    <p class="submitted">
      <!--<?php print $submitted; ?>-->
      <?php print $pubdate; ?>
    </p>
  <?php endif; ?>

  <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished || !$page && $title): ?>
    <header>
      <?php print render($title_prefix); ?>
      <?php if (!$page && $title): ?>
        <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
      <?php endif; ?>
      <?php print render($title_suffix); ?>

      <?php if ($unpublished): ?>
        <p class="unpublished"><?php print t('Unpublished'); ?></p>
      <?php endif; ?>
    </header>
  <?php endif; ?>

  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>

</article><!-- /.node -->

```

# Answer
Just a thought, have you tried using Display Suite?
> 1 votes

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


title: Page id based on file path?

text:
# Question
Title: Page id based on file path?
My page structure looks a little something like this:

* www.site.com/sub-directory-1/page-1
* www.site.com/sub-directory-1/page-2
* www.site.com/sub-directory-1/page-3
* www.site.com/sub-directory-2/page-1
* www.site.com/sub-directory-2/sub-sub-directory-1/page-1
* www.site.com/sub-directory-2/page-2
* www.site.com/sub-directory-2/page-3

What is the easiest way to make the page's ID the name of the first subdirectory it's stored in?

For example, in the first case, the `<body>` tag should be like the following.

```
<body id="sub-directory-1">

```

# Answer
You need to edit your page.tpl.php file, and add this where you have the `<body>` tag.

```
<body class="<?php
   print arg(0, request_path());
?>

```

This will print the first part of `$_SERVER['REQUEST_URI']` delimited by a slash. `arg()` and `request_path()` are Drupal functions.
> 3 votes

---
Tags: 7, uri
---


# Question
Title: Complex Shipping Rule: €3 Flat Rate for order's first 2kilos + extra €1.2/extra kilo charge
Well, the title is quite descriptive about what I'm trying to do with Rules for my e-shop. I have a flat rate for shippable products and I want to charge extra shipping costs to customers according to order's total weight. I'm already using physical fields for weight so I could use the field's value for this rule. Note that some products won't have anything in the weight field and in this case I don't want to take them into consideration for the shipping cost calculation.

So, I want to charge €3 (flat rate's base charge) if the order is 0-2 kilos. In case the total order's weight is more than 2 kilos, I want to add €1.2 to shipping cost for every additional kilo.

e.g. order has 3 products. Product 1 - 2 kilos Product 2 - 0 kilos (or no value in weight field) Product 3 - 2.5 kilos Total order's weight: 2+0+2.5 = 4.5 kilos (ie 2.5 kilos to be charged extra)

So the shipping charge should be €3 (flat rate's base) + €1.2\*2.5 = €6.

I really need some guidance here on how I'm going to make this happen using Rules.

# Answer
One of the problems with Commerce (and Ubercart for that matter) is that it takes awhile for someone to come around with weight based calculations. I have done something similar but it might not work for you.

1) I made each increment I wanted to allow a single product (i.e. 1lb of Product X is 1 QTY, if they want 2lbs of Product X, it's the same as saying Product X with 2 QTY.) 2) Then I created bundles for what I wanted to allow. 3) In shipping, you can set up a rule that allows extra for each extra QTY ($6 for 1 QTY and $2 for each additional QTY.)

For you, it might be possible to set your rule to multiply but you would have to create a module that would allow you to set percentages on QTY if you wanted someone to be able to add 1.2 QTY to their cart. For me, it was easier to do by whole increments and much cleaner on the rules. You can also set your shipping rule to line items so that the first line item is the base and the remaining are the additional.
> 0 votes

---
Tags: commerce, rules
---


title: How to translate comment field label?

text:
# Question
Title: How to translate comment field label?
I'm using the Russian localization for Drupal sites and everything seems to be finely translated **except** the comment form (while viewing a node).

The field "**Subject**" is translated but the field label "**Comment**". I mean, comment's body field displays as "Comment". And what's interesting, I cannot find it in the translation list (for manual translation).

# Answer
> 3 votes
Edit content type \> comment field \> edit \> change the text

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


# Question
Title: Commerce (and Commerce Kickstart) rendering add-to-cart buttons on any page?
Can someone school me or point me to a resource where I can learn how to render the add-to-cart buttons for specific products on any page? I know how to get them in a view and I'm using Commerce Kickstart.

The goal is simple, for the slider, I'd like to include an add-to-cart button for the slideshow product in the slide itself. The slides are content but they're not controlled by a view as Commerce Kickstart has it's own module for the slideshow. Even if it were a view, I don't think it would help.

So is there a way to print out an add-to-cart (even in PHP) like finding the add-to-cart variable for a product by id or something and just rendering it? Thanks.

# Answer
Solved: Experimenting I added a product variation field to the Slideshow content type. This essentially creates a new line item type but that's okay. I can now render the field in the view and it adds to the cart like it's supposed to. Just some CSS now and it will be just fine.
> 1 votes

---
Tags: commerce
---


# Question
Title: Display image fields of a node as slideshow
I have created a content type with some text and image fields. I want to display its images as a slideshow below text fields in view node page of this content type. How can I do it ? Is view slideshow module suitable for this purpose ? or I have to use other module ?

I am working in Drupal 6.

# Answer
Thank you to anyone answered me. I solved my problem with Lightbox2 module. It adds a new option in 'display fields' of content type field management.
> 1 votes

# Answer
Views Slideshow should be *more* than enough for what you need.

**EDIT**

I meant View field, not Views Field View - sorry.

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.
> 4 votes

# Answer
Views slideshow is probably the answer but a lot of people struggle with its setup so you might want to follow this http://www.brightwebsitedesign.com/how-to-install-views-slideshow-module-on-drupal7
> 0 votes

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


title: How to create an Ad Rotator

text:
# Question
Title: How to create an Ad Rotator
In my website, I need to use ad rotator, which have this requirements:

* Allow administrator to manage ads for each page
* Each page may contain different ads
* Administrator may upload more than one ads for each page
* When the user load page, there is only 1 ads will be shown to user and the ads that shown to user may randomly or sequentially load.

For example:

* I have 2 pages, which are page A and B. Then for page A I have 2 ads, which are ads X & Y, and for page B I have 3 ads, which ads ads U, V, & W. When the user load page A, only 1 from 2 ads shown. The ads may randomly or sequentially loaded.
* Let's say, when the first time user load the page, ads Y shown to user, and second time user load the page, ads X shown to user (if ads randomly loaded). Or if the ads sequentially loaded, when the user load page A, then ads X will be shown, after that ads Y, then ads A again, and so on.

My question is:

* Is there any suggestion, which plugin should I use to fulfill my requirements?

Thanks in advance.

# Answer
> 1 votes
Try the SimpeAds module

It allows to define ads categories as a separate taxonomy, and then places ads from a given category in a block. Then you can configure the block to display on a page A and to display random one of the ads from a given category.

---
Tags: 7, advertising
---


title: Force IE Compatitbility Mode

text:
# Question
Title: Force IE Compatitbility Mode
I need to force IE to show my site in compatibility mode, and I know I can just add a META header. The problem is how... can anyone point me in the right direction please? I'm running a custom theme.

Thanks

# Answer
IE has a header for controlling this, X-UA-Compatible. Normally, people set this to 'IE=edge,chrome=1' which disables compatibility mode and tries to force Google Chrome Frame. If you want to emulate IE7, you can use 'EmulateIE7'.

In Drupal 7, it is best to use a hook\_html\_head\_alter for this

```
function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['MYTHEME_ie_compatability'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'name' => 'X-UA-Compatible',
    'content' => 'EmulateIE7',
    ),
  );

  $head_elements['MYTHEME_ie_compatability']['#attached']['drupal_add_http_header'][] =
    array('X-UA-Compatible', $head_elements['MYTHEME_ie_compatability']['#attributes']['content']);
}

```

This sets the `<meta>` in the `<head>` and also sets an HTTP header in the response.

In Drupal 6, you could use

```
function MYTHEME_preprocess_page(&$variables) {
  drupal_set_header('X-UA-Compatible: EmulateIE7');
}

```

You can also do this via Apache (eg, in .htaccess) with

```
<IfModule mod_headers.c>
  Header set X-UA-Compatible EmulateIE7
</IfModule>

```
> 3 votes

---
Tags: 6
---


title: Views exposed pager options

text:
# Question
Title: Views exposed pager options
I need to hide the pager's exposed options (results per page) when the view has no results. I looked everywhere but can't find anything.

Thanks

# Answer
> 0 votes
I ended up hiding it with css and showing it with javascript in case the view returned something.

This way no further server processing is required and is easier to maintain.

# Answer
> 6 votes
There is no intuitive way to do it, but I found a solution using `hook_views_post_execute` and `hook_form_views_exposed_form_alter`:

```
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'MY-VIEW-NAME') {
    // Regenerate the exposed form after execute the view query
    $exposed_form = $view->display_handler->get_plugin('exposed_form');
    $view->exposed_widgets = $exposed_form->render_exposed_form();
  }
}

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = &$form_state['view'];
  if ($view->name == 'MY-VIEW-NAME') {
    if ($view->total_rows == 0) {
      // Hide 'results per page' when the view has no results.
      $form['items_per_page']['#access'] = FALSE;
    }
  }
}

```

# Answer
> 3 votes
Copy 'sites/all/modules/views/theme/views-exposed-form.tpl.php' file in your custom theme folder and modify this section:

````
   <?php if (!empty($items_per_page)): ?>
      <div class="views-exposed-widget views-widget-per-page">
        <?php print $items_per_page; ?>
      </div>
    <?php endif; ?>

````

However, this is the exposed filters form, so you don't have any results to work with. You'll have to build a basic query and test if there are entries in the database.

# Answer
> 2 votes
Turns out the answer to this **depends on whether you have other exposed form elements** that you want to be shown when there are no results.

---

**If you *do* have other exposed form elements**, use **smartinm**'s solution on this page, which preserves the submit button, surrounding markup, and other elements if there are any.

**FREE BONUS**: If you'd also like to not show options that wouldn't do anything because there aren't enough results, use this code below. (for example, with this, if your options are 15, 30, 45, All, then this will show just 15, 30 and All if there are 32 results, and only 'All' if there are 3 results). This is a good UX practice - you're not giving the user broken buttons or the misleading impression there are more results when there aren't, and also, if all results are being shown, it tells them so:

```
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'MY-VIEW-NAME') {
    // Regenerate the exposed form after execute the view query
    $exposed_form = $view->display_handler->get_plugin('exposed_form');
    $view->exposed_widgets = $exposed_form->render_exposed_form();
  }
}

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = &$form_state['view'];
  if ($view->name == 'MY-VIEW-NAME') {
    if ($view->total_rows == 0) {
      // Hide 'results per page' when the view has no results.
      $form['items_per_page']['#access'] = FALSE;
    } else {
      foreach($form['items_per_page']['#options'] as $index => $string) {
        $results_option = (int)($string);
        if( $results_option > $view->total_rows ) {
              // Don't offer to show X results if there are <X results to show
            if (isset($_GET['items_per_page']) && (string)$_GET['items_per_page'] == (string)$results_option ) {
              // Prevent "An illegal choice has been detected" error, don't show meaningless selection in UI
              unset($_GET['items_per_page']);
            } else {
              unset( $form['items_per_page']['#options'][$index] );
            }
        }
      }
    }
  }
}

```

---

**If you *don't* have any other (non-pager) exposed form elements**, then that other code will leave markup and submit buttons that don't do anything. Use something simpler like this which removes the entire form, including submit button and surrounding markup (tested on a setup showing the view as a context view in ctools page manager, results in other setups may vary):

```
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'MYVIEW') {
    if ($view->total_rows == 0) {
      unset( $view->exposed_widgets );
    }
  }
}

```

**FREE BONUS**: If you'd also like to not show options that wouldn't do anything because there aren't enough results (see above), use this:

```
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'MYVIEW') {
    if ($view->total_rows == 0) {
      unset( $view->exposed_widgets );
    } else {
    // Regenerate the exposed form after execute the view query
      $exposed_form = $view->display_handler->get_plugin('exposed_form');
      $view->exposed_widgets = $exposed_form->render_exposed_form();
    }
  }
}

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = &$form_state['view'];
  if ($view->name == 'MYVIEW' && $view->total_rows > 0 ) {
    foreach($form['items_per_page']['#options'] as $index => $string) {
      $results_option = (int)($string);
      if( $results_option > $view->total_rows ) {
          // Don't offer to show X results if there are <X results to show
        if (isset($_GET['items_per_page']) && (string)$_GET['items_per_page'] == (string)$results_option ) {
          // Prevent "An illegal choice has been detected" error, don't show meaningless selection in UI
          unset($_GET['items_per_page']);
        } else {
          unset( $form['items_per_page']['#options'][$index] );
        }
      }
    }
  }
}

```

---

There might be a way to use one set of code for both: loading the form *array* in `_views_post_execute()` somehow, pumping the form contents through `element_children()` and counting to see if there are any elements other than items\_per\_page, submit, etc - removing the whole form if there aren't. I couldn't find anything simple however, also, anything based on that would break if there were any changes to the number of standard elements in an exposed form. Simply removing the submit doesn't work - it leaves all the empty markup for the form.

---
Tags: 7, views
---


title: hook_boot and Varnish

text:
# Question
Title: hook_boot and Varnish
I have a module that implements a hook\_boot(), and it checks if user is going to access home page and if user does not have a specific cookie. If both verifications are true, it redirects user to a /welcome page and set cookie. So the second time a user tries to access home page, it will see that user has the cookie and will not redirect.

Recently, I installed Varnish on my site, and everytime I try to access home page, I get to /welcome page. It never skips.

I'm not sure but it looks like the first time I access home page, when I still don't have cookie, it caches the home page, shows /welcome page and set cookie. Then, second time I try to access home, it gets the cached page (which thinks I don't have cookie) and redirect again to /welcome page, even though I have cookie.

I tried not caching home page but it didn't work.

Any thoughts?

# Answer
> 2 votes
If you use Varnish - you must consider that for anonymous users PHP code will not execute at all - they will retrieve only static HTML.

In you case solution can be as following:

1. On welcome page set cookie by JavaScript not PHP.
2. Using Varnish vcl script check if user loads homepage and has cookie. If not - then redirect it to welcome page.

Now item #2 is made in PHP code but you need rewrite it using Varnish. You can also write item #2 using JavaScript but it will work much slower and user will see browser redirection.

---
Tags: 6, caching, cookies, proxies
---


title: Article voting with feedback option

text:
# Question
Title: Article voting with feedback option
I am attempting to setup an article voting system with the ability to provide feedback to the author. Only admins will be able to see feedback so I do not want it like a review attached at the bottom of each article. My idea was to create a view that only admins had permission to see. Include in this view would be the article name, rating, and feedback if any was submitted. I would like to be able to group the feedback/ratings by article instead of by entry or user and provide an overall calculated rating for the article.

It looks like fivestar is able to do some of this however I do not believe the advanced instructions:"Configuration as a CCK field / Advanced Rating" are for drupal 7. I have created a content type of "Article Feedback" and attempted to follow this answer of how to set something similar up however I do not see anywhere when I create the rating field a "voting target". I do not really understand how Node Reference works and how it will work with the desired result I stated at the beginning of this question.

I am open to using different modules and writing my own PHP script to accomplish this task. Any direction on how to accomplish this is much appreciated.

# Answer
I ended up using the built in drupal comment system as the feedback and just hid the comments from everyone but admins. I used fivestar for the star rating system attached to comments.
> 2 votes

---
Tags: 7, rating
---


# Question
Title: drupal 7 error: table blocked_ips not found
I have a running Drupal 7 site and wanted to restore it locally on development computer. But on localhost I keep receiving white screen in Firefox or Internal Server Error code 500 on Chrome.

Debugging shows that Drupal is running line 1895 of bootstrap.inc, which says:

```
$denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();

```

And just after this line it jumps to error handler, complaining about missing blocked\_ips table. The blocked\_ips table is not there on either site, the production site had no problem with it.

How to deal with this?

# Answer
> 1 votes
The `blocked_ips` table is created unconditionally by the system module...it should be there in any standard D7 install.

The process goes like this:

So Drupal is expecting that table to exist. The only caveat is that if you have a variable called `blocked_ips` in the variable table the value from there will be used instead of the database being queried. Maybe you have that variable on the local version, and not on the live, and the issue is being masked by that fact?

If you didn't have any data in that table then it would be safe to copy the schema from an empty Drupal install and just create the table.

However, it might be worth checking the integrity of the rest of your data as it sounds like something's gone wrong either on your local copy or during the migration.

# Answer
> 0 votes
Your local development DB has been damaged. Luckily, this is not your production site. Just download your production database and import it into your development site.

To backup your dtabse you can use several tools: form phpMyAdmin to "drush sql-dump" drush command or the handy module Backup and Migrate. To import you the same tools (but use "drush sql-cli" and pipe the DB content if you use drush, instead of sql-dump, for obvious reasons).

# Answer
> 0 votes
In your `settings.php` file you have a `blocked_ip` index in the `$conf` array. If you uncomment this you bypass the `'blocked_ip'` table query. It's possible that the production site has this change but not your local.

E.g. production `settings.php` (around line 440):

```
$conf['blocked_ips'] = array(
  '',
);

```

The array could also contain a list of IP's.

Your local `settings.php`:

```
# $conf['blocked_ips'] = array(
#   'a.b.c.d',
# );

```

# Answer
> 0 votes
I have also encountered such kind of situation when cloning my site into my local development server. When I downloaded sql dump files for each module by module and imported them into my localhost, it did work for me.

Firstly, about white screen, check this answer. Then, Drupal will display errors on the screen.

Then, download sql dump files for each module by module, for example, the block module has 4 modules - block, block\_custom, block\_node\_type, block\_role. Export those 4 tables in a sql file and same for other modules. Most likely, tables in the same module have same prefix. Import them all into your localhost each by each including the system and variables tables.

Note that the cache tables should be exported and imported by structure only.

---
Tags: 7, bootstrapping
---


title: Entity API fieldable entity path issue

text:
# Question
Title: Entity API fieldable entity path issue
So, after studying several examples, I started writing my own module to implement a notification-like entity.

I wanted it to allow separate bundles and be fieldable. This example was a great guide to me.

I've spend several hours and almost brought the wall down with my head due to the following issue though.

My implementation of `hook_entity_info_alter`:

```
function mymodule_entity_info_alter(&$entity_info) {
  foreach (notification_types() as $type => $info) {
    $entity_info['notification']['bundles'][$type] = array(
      'label' => $info->label,
      'admin' => array(
        'path' => 'admin/structure/notification-types/manage/%notification_type',
        'real path' => 'admin/structure/notification-types/manage/' . $type,
        'bundle argument' => 4,
      ),
    );
  }
}

```

to provide admin UI for my bundles, wouldn't work. It would provide "Manage Fields" and "Manage Display" tabs in my `/admin/structure/notification-types` list page with "broken" links such as `/admin/structure/notification-types/manage/%25notification_type/fields`.

Furthermore when I tried to manage fields of my bundles, I got a "page not found" error.

When I changed the 'path' array element to this:

```
'path' => 'admin/structure/notification-types/manage/%',

```

all of a sudden it worked, the wrong tabs went away and the bundles were manageable. My question: Why?!

# Answer
GOT IT! After googling for a while I came accross this: http://drupal.org/node/224170

This clarifies that

"When a % symbol is used in a menu element (see example), the text that follows will be used to build the name of wildcard loader function.

In the example above, "%node" tells drupal to pass the value of the second element to the function node\_load(). \_load is always added by Drupal to construct the wildcard loader."

So as long as the notification\_type\_load() function wasn't implemented it lead to a bug :)
> 1 votes

---
Tags: 7, entities, routes
---


# Question
Title: Is there a "description" field for Rules actions?
I have several rules that are very complicated and have many steps. Even though I am the only web developer, I often have to study rules I have written a bit to remember how they work.

Does the Rules module have "description" fields somewhere like Views so developers can make notes to other developers/themselves? Surely other people must have this same problem...

# Answer
> 1 votes
This is so needed. I agree. Luckily, it's in the works: http://drupal.org/node/1244738

I'd add your vote to that Drupal module issue! :-)

---
Tags: rules
---


# Question
Title: How to set one of the fields displayed in the view to be a link to a webform submission?
I'm using the Webform MySQL Views module to allow me to display webform submission data in views. This works really well; once you get it set up you work with the view just like you would a normal one.

So here's my question: how can I set one of the fields displayed in the view to be a link to the webform submission? There's an option to make a field a link in the Rewrite Results section:

But I'm not sure how to enter the path to the actual submission. The link I need to produce looks like this (copied from Content-\>Webforms-\>Submissions-\>View):

```
http://localhost/drool_calendar/node/1/submission/5

```

I'm guessing I don't need to specify the server or site name, but everything from `node/` on.

# Answer
This is an old post, so I expect you found your answer already. You need to have the post's id number. Try adding that field to the set, but excluding it from view. Also, rearrange fields so it is earlier in the list than the field you are turning into the link. You should then be able to use replacement tokens to make the path entry look something like:

/drool\_calendar/node/\[content:nid\]/submission/\[content:subid\]

Starting the path with a / tells Drupal that you want this to stem from the site base url; discarding the leading slash tells Drupal you want this link to stem from the current page.
> 1 votes

---
Tags: 7, views
---


# Question
Title: What module is used to create the table of contents in Drupal documentation?
I want to create a table of contents for sections of my site like Drupal.org has for their documentation. For example on this page, there is the "Table of Contents" block on the right hand side. What module is used to do this?

# Answer
> 3 votes
That block is the "Book navigation" block implemented by the Book module in book\_block\_view(), and defined in book\_block\_info().

The copyright block that appears right after the "Book navigation" block is implemented in drupalorg\_handbook.module, which is a custom module used to run Drupal.org, and its sub-domains.

---
Tags: 7
---


title: How to implement menu in footer blcok

text:
# Question
Title: How to implement menu in footer blcok
I need a (D7) block print the main menu in the footer; It's not clear to me how the pieces fit together:

We implement block\_info, block\_view, a pre-process function and a template.

```
function MODULE_NAME_block_info() {
  $blocks['my-footer-menu'] = array(
    'info' => t('My Footer'),
  );
  return $blocks;
}

function MODULE_NAME_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my-footer-menu'
     $tree = menu_tree_page_data('main-menu');
     $block = array( 'subject' => t('My Footer'),
                  'content' => theme('my-footer-menu', $tree),
      );
    break;
 }
return $block;
}

function MODULE_NAME_theme() {
  return array(
    'my_footer_menu' => array(
    'template' => 'my-footer-menu',
    'variables' => array('tree' => NULL),
  ),
);
}

function template_preprocess_my_footer_menu(&$variables) {
  $variables['tree'] = menu_tree_all_data('main-menu');
}

<?php
  for ($i = 0; $i < count($tree); $i++) {
    $menu = each($tree);
     if ($menu) {
        $link = array( '#theme' => 'link',
                'title' => $menu[1]['link']['link_title'],
               'href' => $menu[1]['link']['link_path']);
          print '<a href="'  . $link['href'] . '">' . $link['title'] . '</a>';
        //  $output = theme( 'links', $link);  //this isn't right
        //  print $output;    //returns an empty string;
        }
      }
 ?>

```

The above gets the top level menu items on the page, but it's not clear how to get to the children of each menu item. Sorry if it seems a bit muddled, just trying to cut my way through the weeds here.

# Answer
You can create all of the code yourself, but you could also use the menu block module instead and save yourself a lot of work.
> 0 votes

---
Tags: routes, blocks
---


# Question
Title: How can I have all drupal links work on ajax based?
Is it possible to have all drupal internal links work on ajax based without any page refresh?

If there is any ready module, please share the link. Your help is really appreciated.

# Answer
Maybe this module will help you: http://drupal.org/project/ajax\_links\_api

> Ajax links API module help you to load any content to a specified DIV using JQuery Ajax. This module will also load JS and CSS for Ajax-loaded content by using Drupal.attachBehaviors(). Links will work as normal if Javacript is disabled.
>
> In HTML5 browsers, title bar and url will change using window.history.replaceState() (This feature is disabled by default. Check ajax\_links\_api.js to enable).
> 2 votes

---
Tags: 7, ajax
---


# Question
Title: How to render Views anchors with `title` attribute?
By default the Views module doesn't put `title` attributes on anchors as it only puts them on anything that has an `alt` attribute.

Seeing as you're not likely to have an `alt` attribute on a standard anchor. Could someone please advise what you need to do in order to render Views anchors with `title` attribute?

# Answer
> 1 votes
You can supply your own 'alt' attribute (and thus 'title' when rendered) by outputting your field as a link. Choose "Output this field as a link", and enter the path, and alt text from the available tokens. Sometimes you might have to define a separate 'path' field for use in the 'link path' value. You might also have to experiment with the "Use absolute path" setting to get the href right.

# Answer
> 2 votes
You can do this:

In your `Content: Title` expand `Rewrite Results` and check `Rewrite the output of this field`

In the Text field enter: `<a id="[title]">[title]</a>` This will create your anchor jump point.

Next you can add a block and repeat the same process replacing Text field with `<a href="#[title]">[title]</a>`

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


# Question
Title: Is there any reason Backup & Migrate leaves all the .info files around?
I just discovered that there are hundreds of `.info` files left lying around in the folder that the Backup & Migrate module uses for scheduled backups, while only 12 of these have a corresponding `.gz` file.

Is there a reason to keep these? Do they have any real value?

# Answer
> 1 votes
There doesn't appear to be any value to keeping them. To get rid of them, you can do something like this

```
cd /private/backup_migrate/scheduled  # where ever you keep this
for file in *.info; do gz_file=`echo "$file" | sed -e 's/.info//'`; if [[ ! -f "${gz_file}" ]]; then rm -f "${file}"; fi; done

```

This will preserve all `*.info` files that correspond to a `*.gz` file, and delete the rest. It *appears* to be an oversight on the part of the Backup & Migrate module to leave all of these lying around. (Apologies in advance to the module's maintainers if I'm mistaken on this: I do not mean to be critical, and I appreciate your work!)

If you want to wrap all this up into a quick alias or function, you can put something like this into your `~/.bashrc` or `~/.zshrc` or whatever:

```
function cleanup_backups(){
  pushd /<youfillinthispart>/private/backup_migrate/scheduled
  for file in *.info; do
    gz_file=`echo "$file" | sed -e 's/.info//'`
    if [[ ! -f "${gz_file}" ]]; then
      rm -f "${file}"
    fi
  done
  pushd
}

```

(You'll have to make it a bit more complicated if you have subdirectories in your scheduled backups folder, but this should get you started.)

---
Tags: backups
---


# Question
Title: Rules- How can I copy the formatted text in one field to another?
I need to move the values of a field (long text and summary) to another field (long text and summary). I am trying to do this with Rules and VBO.

I have fetched nodes A and B, and I want to set the value of the field in B to the value of the field in A.

The challenge is that I can't use the *Set a data value* action to simply set B to A. I can use Rules to create a *text* variable and get the value from A that way, but I still can't set that *text* variable as the value (Rules requires a *formatted text* variable). However, if I try to create a *formatted text* variable, I can't set the value of the *Long text and summary* field as the value.

I have the two nodes available in Rules and they both have fields of type *Long text and summary*. I just want to set the value of B to the value of A. How can I do this?

# Answer
> 2 votes
I figured it out-- I needed to add :value after the body field, since the field value contains the summary, text format, and text value.

So for example, instead of *profile:field-myfield*, use *profile:field-myfield:value*.

---
Tags: rules
---


# Question
Title: How do I display multilingual logos in D7?
I have read almost every tutorial on the net about how to setup multilingual logos. Yet, I cannot get anything to work.

How do I get multilingual logos to display in D7? I have added

```
$conf['i18n_variables'] = array(
    'logo_path',
    'theme_XXX_settings',
);

```

I have also uploaded using the form for the theme settings while in the langauge of the logo I want to display. All languages are set to whatever file I upload last.

Do I need to use a different variable in the conf array? Do I need to print a different variable other than $logo in the theme?

Can someone who's done this give some very specific instructions or provide a link to a recent d7 tutorial?

# Answer
For D7, this is very painless.

In i18n, enable 'Variable Translation' module. To do so, be sure to have at least variable 7.x.2.x, else this module is not available. Here is the text from the module page:

```
Multilingual variables that switch language depending on page language.
Requires: Internationalization (enabled), Locale (enabled), Variable
(enabled), Variable store (7.x-2.x) (incompatible with version 7.x-1.2),
Variable realm (7.x-2.x) (incompatible with version 7.x-1.2)

```

After that, go to:

configuration-\>Multilingual settings-\>variables (tab)-\>Theme settings. check the boxes. Then go to your theme and set a logo for each language.

That's it!
> 8 votes

---
Tags: 7, media, i18n-l10n
---


title: Using LIKE in db_query in D7

text:
# Question
Title: Using LIKE in db_query in D7
I have a query like this in Drupal 6:

```
$sql = 'SELECT sid, score FROM search_index WHERE word LIKE "%%%s%%"';
$result = db_query($sql,$search_term);

```

And it worked fine, but now I'm upgrading to Drupal 7.

I read up and this is supposed to work, but it's not:

```
$sql = 'SELECT sid, score FROM search_index WHERE word LIKE "%:term"';
$result = db_query($sql,array(':term'=>$search_term));

```

Does anyone know what I'm doing wrong?

# Answer
Try this.

```
 $sql = 'SELECT sid, score FROM {search_index} WHERE word LIKE :term';
 $result = db_query($sql, array(':term' => '%' . db_like($search_term)));

```
> 20 votes

# Answer
If you followup the the following link, http://api.drupal.org/api/drupal/includes!database!database.inc/group/database/7 This will tell you that,

> Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself.

So

```
SELECT nid, title FROM {node} WHERE title LIKE :title%;

```

Is incorrect.

The query should be

```
SELECT nid, title FROM {node} WHERE title LIKE :title;

```
> 0 votes

---
Tags: 7, database
---


# Question
Title: Selecting English from language selector fails
I have setup a multilingual website using the i18n and domain access modules. Each country has its own domain and on a few of these domains multiple languages are available. eg. fr.domain.com has the available languages French, English, German and Dutch with French being the default. When selecting English as a language from the language selector on this French domain the translation fails and instead either loads the domains default language or I receive a 'Page Not Found' error. I have checked that all English content is available on this domain. All other languages translate correctly when selected from the drop down.

I'm really not sure where to go from here as I'm not too familiar with i18n modules so any help would be appreciated.

# Answer
* Go to Configuration and choose Languages.
* Edit 'English' language
* Add 'en' in 'Path prefix language code' filed
* save and flush all cache
> 0 votes

---
Tags: i18n-l10n, domain-access
---


# Question
Title: Getting a taxonomy-term-name as plain-text in computed field
In an entity-type with term-reference i want to add a computed field, which grabs the term and sanitizes it for further use with the drupal\_clean\_css\_identifier for example. My code doesn't work, because field\_get\_items gives back a full link to the term instead the term name as plaintext:

```
$entity_field[0]['value'] = drupal_clean_css_identifier(array_pop(field_get_items($entity_type, $entity, 'field_myterms'))));

```

Can someone help me out?

# Answer
> 3 votes
calling field\_get\_items() on a term reference field returns an array like this

```
Array(
  0 => Array(
    'tid' => 10,
  ),
)

```

to get the term name from the term id (tid) you should load the taxonomy term:

```
$field_myterms = field_get_items($entity_type, $entity, 'field_myterms');
if (!empty($field_myterms)) {
  $term = taxonomy_term_load($field_myterms[0]['tid']);
}

```

$term is an stdClass object:

```
stdClass Object
(
    [tid] => 1
    [vid] => 1
    [name] => test
    [description] =>
    [format] => filtered_html
    [weight] => 0
    [vocabulary_machine_name] => tags
    [rdf_mapping] => Array
        (
            [rdftype] => Array
                (
                    [0] => skos:Concept
                )

            [name] => Array
                (
                    [predicates] => Array
                        (
                            [0] => rdfs:label
                            [1] => skos:prefLabel
                        )

                )

            [description] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:definition
                        )

                )

            [vid] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:inScheme
                        )

                    [type] => rel
                )

            [parent] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:broader
                        )

                    [type] => rel
                )

        )

)

```

to set the computed field value:

```
$entity_field[0]['value'] = drupal_clean_css_identifier($term->name);

```

---
Tags: entities
---


# Question
Title: How to structure git repositories for project?
I'm working on a content synchronisation module for Drupal. There is a server module, which sits on ona website and exposes content via a web service. There is a also a client module, which sits on a different site and fetches and imports the content at regular intervals.

The server is created on Drupal 6. The client is created on Drupal 7. There is going to be a need for a Drupal 7 version of the server. And then there will be a need for a Drupal 8 version of both the client and the server once it is released next year.

I'm fairly new to git and source control, so I was wondering what is the best way to setup the git repositories? Would it be a case of having a separate repository for each instance, for example:

```
Drupal 6 server = 1 repository
Drupal 6 client = 1 repository
Drupal 7 server = 1 repository
Drupal 7 client = 1 repository
etc

```

Or would it make more sense to have one repository for the server and another for the client then create branches for each Drupal version?

Currently I have 2 repositories: one for the client and another for the server.

# Answer
Drupal.org uses just one repository for module, and branches for each module version (for example, 7.x-1.x for module in version 1.x for Drupal 7, 6.x-1.x for module in version 1.x for Drupal 6, 7.x-2.x for module in version 2 for Durpal 7, and so on).

Also, if your server and client share code you may use just one Durpal module with submodules, so all code is in one repository. Users will just enable client or server (and the module that holds the common code).

So, your actual setup is fine if client and server do not share any code or very little and you want to keep them as separate modules. Just add branches for each Drupal version (6.x, 7.x, 8.x). Or join them into one repository and split code into three modules: common, server and client.

You can check the 'Maintaining a drupal.org project with Git' page.
> 8 votes

# Answer
You can do it like you want really - there isn't really a right or wrong way of doing it.

Personally I would have 2 repos and use branches for different versions. This is also how Drupal does it with modules. They have seperate branches for Drupal 6, 7 and 8 release. Most also have seperate branches for major releases, fx `7.x-1.x` and `7.x-2.x` being two different branches.

If you have different teams working on the Drupal 6, 7 and 8 versions, you could use separate repos to manage access control. But like I said, there isn't really a right or wrong way of doing this, it really depends on how your team works and how you want/need to administer it.

If you are new to git you might want to read about the git branching model, it's a great blog post about working with git.
> 5 votes

---
Tags: version-control
---


# Question
Title: Use the panel for layout with multiple columns
I created my own content type. I would like to further customize it by adding columns. I installed the module panel. Can I use the same panel layout to include my content type? Also, how do I put a picture in a field of the panel?

# Answer
> 1 votes
I would use panels for layout of a page which contains various bits and pieces from other pages. For layout of the display of a single page or node type I would edit the templates page--content-type.tpl.php and node--content-type.tpl.php.

In node--content-type.tpl.php you could then do something like:

```
<div class="col1">
<?php
  // Hide fields so that we can render them later.
  hide($content['field_image_main']);
  print render($content);
?>
</div>
<div class="col2">
  <?php print render($content['field_image_main']);?>
</div>

```

# Answer
> 1 votes
Following your previous comments, it seems like you want Display Suite rather than Panels.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

There's also an absolutely cracking series of video tutorials here that will help you set it up and configure it.

---
Tags: theming, 7
---


# Question
Title: Title changed programmatically is not put into breadcrumbs
I have 2 functions in template.php: The first attaches current page title to breadcrumbs; the second sets the title to 'Completion' when the user opens /scores/completion.

```
function lwt_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];
    if (!empty($breadcrumb)) {
        // Adding the title of the current page to the breadcrumb.
        $breadcrumb[] = drupal_get_title();

        // Provide a navigational heading to give context for breadcrumb links to
        // screen-reader users. Make the heading invisible with .element-invisible.
        $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

        $output .= '<div class="breadcrumb">' . implode(' » ', $breadcrumb) . '</div>';
        return $output;
    }
}

function lwt_preprocess_page(&$vars) {
      $path = drupal_get_path_alias();
      if ($path == 'scores/completion') {
            $vars['title'] = 'Completion';
      }
}

```

The breadcrumb is still scores. How do I fix it?

# Answer
> 3 votes
drupal\_get\_title() gets the title from a PHP static variable, which is different from the variable `$variables['title']` passed to the template files.

Your template hook would work if it uses the following code.

```
function lwt_preprocess_page(&$vars) {
  $path = drupal_get_path_alias();
  if ($path == 'scores/completion') {
    // -1-
    $vars['title'] = t('Completion');
    drupal_set_title($vars['title']);
    // -1-
  }
}

```

What happens is the following:

* `lwt_preprocess_page()` is invoked, and (through drupal\_set\_title()) sets the static variable containing the value returned from `drupal_get_title()`.
* template\_process\_page() is invoked, and it calls the theme function for the breadcrumbs; in your case that theme function is `lwt_breadcrumb()`, which calls `drupal_get_title()`, obtaining the same value you set in `lwt_preprocess_page()`.

In `lwt_preprocess_page()` you could also replace the code between `// -1-` with the following one.

```
    unset($vars['title']);
    drupal_set_title(t('Completion'));

```

The reason also this code works is that `template_process_page()` first checks if `$variables['title']` is set; if it is not set, it calls `drupal_get_title()`.

```
  if (!isset($variables['title'])) {
    $variables['title'] = drupal_get_title();
  }

```

### References

* theme(), for the order in which theme template hooks are executed
* drupal\_static(), for understanding how the page title is stored in a static variable accessible to any function

---
Tags: 7, breadcrumbs
---


# Question
Title: Can I allow a user to add additional tabs in quicktabs?
In the same way that we can set a field to unlimited, allowing a user to add more than one value, might there be a way to do the same using quicktabs?

# Answer
Well, this is not so much about quicktabs, but I did find a work around. I ended up using plain old field groups. This module has logic in it where if containing fields have no content, don't display that tab (or "horizontal item" in this case).
> 0 votes

---
Tags: blocks, entities
---


title: Custom Install.php template

text:
# Question
Title: Custom Install.php template
In the process of developing a distribution, I'm stuck with the task to customize the install.php page. Can't find a way to change the tpl/layout of the installation process or which preprocess function to use.

I'd like to do the same as Commerce Kickstart did, in a certain way.

Any ideas how?

# Answer
> 3 votes
Here's the trick that Kickstart uses (from commerce\_kickstart.install). The actual styling is in the Shiny admin theme.

```
/**
 * Implements hook_install_tasks_alter().
 */
function commerce_kickstart_install_tasks_alter(&$tasks, $install_state) {
  _commerce_kickstart_set_theme('shiny');
}

/**
 * Force-set a theme at any point during the execution of the request.
 *
 * Drupal doesn't give us the option to set the theme during the installation
 * process and forces enable the maintenance theme too early in the request
 * for us to modify it in a clean way.
 */
function _commerce_kickstart_set_theme($target_theme) {
  if ($GLOBALS['theme'] != $target_theme) {
    unset($GLOBALS['theme']);

    drupal_static_reset();
    $GLOBALS['conf']['maintenance_theme'] = $target_theme;
    _drupal_maintenance_theme();
  }
}

```

# Answer
> 1 votes
Have you reviewed the code used in the Commerce Kickstart distribution? They don't really change the "layout". What they did was they modified the glbal variable in kickstart that stores the theme used:

```
if ($GLOBALS['theme'] != $target_theme) {
    unset($GLOBALS['theme']);

    drupal_static_reset();
    $GLOBALS['conf']['maintenance_theme'] = $target_theme;
    _drupal_maintenance_theme();
  }

```

---
Tags: theming, installation, commerce, distributions
---


title: How can I disable account settings?

text:
# Question
Title: How can I disable account settings?
I am using Drupal 6 with the OpenAtrium distribution, and I'd like to completely remove the account settings menu. In other words, I don't want users (or, even better, certain users) from access account settings. I know that it can be done by hiding the menu via CSS, but I am looking for some kind of module that can make it easier.

EDIT:

Ok what I did was creating and activating a new module called disablepermissions:

```
function disablepermissions_menu_alter(&$items){
     $items['user']['access callback'] = FALSE;
     $items['user/%user/edit']['access callback'] = FALSE;
     $items['user/%user']['access callback'] = FALSE;
}

```

This actually works as intended but if I try to set some kind of permissions I only get a blank page with a 500 Internal Server Error, why? The following code does not work...

```
function disablepermissions_perm() {
    return array('visualizza utenti');
}

function disablepermissions_menu_alter(&$items){
     if (access_user('visualizza utenti') {
     $items['user']['access callback'] = TRUE;
     $items['user/%user/edit']['access callback'] = TRUE;
     $items['user/%user']['access callback'] = TRUE;
     }
     else {
     $items['user']['access callback'] = FALSE;
     $items['user/%user/edit']['access callback'] = FALSE;
     $items['user/%user']['access callback'] = FALSE;
     }
}

```

# Answer
> 1 votes
You could use hook\_menu\_alter(). Something like this should work:

```
function yourmodule_menu_alter(&$items){
  $items['user/%user_category/edit']['access callback'] = 'yourmodule_user_custom_access_function';
}

function yourmodule_user_custom_access_function($u){
  return user_access('administer users');
}

```

This way, only users with "administer users" permissions will be able to edit user informations.

---
Tags: distributions, users
---


title: Panels, menus, and path in Drupal 6

text:
# Question
Title: Panels, menus, and path in Drupal 6
I'm trying to work on a site that's using Panels to, among other things, create a sidebar navigation menu. It's working well on a page that exists in the menu tree structure:

* Primary links
    + Info Page
        - One type of info
        - Another type of info
    + **Updates**
        - One category of updates
        - Another category of updates
    + Another page
        - With some subpages
        - Of its own

On the **Updates** the menu (correctly) appears as such:

* Info Page
* **Updates**
    + One category of updates
    + Another category of updates
* Another page

I want to create essentially the same structure, with only a selected part of the menu expanded, but on pages that are not themselves part of the menu structure (i.e. individual updates within the categories of updates). Ideally I'd like to do this based on the path alias or content type or something of that nature, so all updates show a menu with the whole updates category expanded (but not Info or Another)

How do I do this with Panels in 6.x?

# Answer
> 0 votes
I ended up doing this with the Menu Position module and Menu Blocks module as well as Panels.

1. Create a Menu Block with
* Parent item:
        + Menu: Primary Links
        + Item: \<root of primary links\>
        + Starting level: 2nd level (secondary)
2. Create a Menu Position rule:
    * Content Types:
        + Update
    * Menu item:
        + Updates
3. Add your menu block as panels content (if desired) to the nodes of the desired type.

---
Tags: 6, routes, panels
---


# Question
Title: Where is the information in the node_info hook displayed in drupal
I am beginning with drupal. I cannot see where the information which I write in the hook node\_info displayed in drupal. What is the link to check it?

# Answer
> 0 votes
You should see it on the add content page. If you don't, either you need to clear cache, the module isn't enabled, or the module is coded incorrectly.

---
Tags: hooks
---


# Question
Title: How to create a URL with $_GET values by writing my own custom module?
I am writing my own module and I would like to know how to create a URL from a search form that utilizes $\_GET requests so I can pass those arguments into my query.

The Views module is a good example. For example, after you create a view and have exposed filters, your Views URL would look like:

```
CustomView?field_data_field_year=2012&field_data_field_month=december

```

Currently my hook\_menu looks like:

```
function papers_pub_search_menu() {
  $items['papers_pub_search'] = array(
      'title' => 'Papers and Publications Search',
      'description' => 'Search Papers and Publications',
      'page callback' => 'papers_pub_search_viewer',
      'page arguments' => array(1,2),
      'access arguments' => array('access papers and pub search'),
      'type' => MENU_CALLBACK,
  );
  return $items;
}

```

My problem is the 'page arguments' =\> array(1,2). It seems like the format of the URL would be "foo/bar" and it would strictly need 2 arguments. My user may pass 1 or 3 arguments based on what parts of my form fields they fill out.

Another simple example, if I wanted to do this in pure PHP, it would be trivial:

```
<?php
if($_GET['submit']) {
  $name = $_GET['name'];
  $query = "SELECT name FROM user WHERE name = $name";
  ...
}
?>
<form action="form.php" method="get">
  <input type="text" name="name">
  <br>
  <input type="submit" name="submit" value="submit">
</form>

```

What I am trying to do is create a form where a user can fill out some fields, and then do some DB query based on what the user has inputted into various text fields and pull down choices once they hit submit.

# Answer
> 3 votes
If I understood your question correctly, you are mixing the URL arguments and query string.

You can have as many query string arguments as you want and you do not have to define them upfront. Drupal will not limit you. An example of query string is `page?arg1=123&arg2=456`, just like what views module does for filters. This is what you need for your `$_GET` form.

What you define in the `hook_menu` are URL arguments - for example `one/two/three`. You can get them by using the `arg()` function, so `arg(0)` in the example above would return `one`, `arg(1)` would return `two` etc.

---

**UPDATE**

> So is the URL arguments in hook\_menu not needed (i.e. page arguments)?

Yes, you don't need it in this case. You will solve everything by using query string (~question mark in the URL).

> Does 'page?arg1=123&arg2=456' not count as an argument, or is that just one big argument (i.e. arg(0))?

That is only one argument. `arg(0)` would return just `page`. `arg1` and `arg2` are query string parameters.

Think of page argument as a part of the base URL for the page.
Query string is what goes after the question mark.

You should use `filter_input()` instead of simple `$_GET` as it is much more secure.

See also `drupal_get_query_parameters()`.

---
Tags: 7, routes
---


title: Issues with update hook in drupal 6

text:
# Question
Title: Issues with update hook in drupal 6
I have this purchase module defined. And I have implemented the update hook something like this

```
<?php
  function purchase_update($node) {
    echo 'Updating';
    exit(0);
  }

  function purchase_help($path, $arg) {
    $output = '';
    switch ($path) {
      case "admin/help#purchase":
        $output = '<p>'.  t("Update help") .'</p>';
        break;
    }
    return $output;
  }

```

However, whenever I edit a node of type purchase, it doesn't call my update function. Any suggestions what could go wrong?

# Answer
> 1 votes
Did the purchase-module create and implement the entire purchase node type or did you create that in the admin system?

If you created it in the admin-system you can't use those functions. They are for node type modules (a rarer and rarer kind of module use these days).

You probably want hook\_nodeapi. It's a common misconception. http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook\_nodeapi/6

```
function hook_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'update':
      if($node->type == 'purchase') {
        echo 'Updating';
        exit(0);
      }
    break;
  }
}

```

---
Tags: hooks, entities
---


# Question
Title: Building a username search by writing custom module
My module simply allows a user to type in a user ID # in a field and hit the submit button. The page should return the username.

```
function usersearch_form_submit($form,&$form_state) {
  $query = "SELECT name FROM users WHERE uid = :uid";
  $result = db_query($query,array(':uid' => $form_state['values']['uid']));
  foreach($result as $user) {
    echo "The username is $user<br>";
  }
  $form_state['rebuild'] =  TRUE;
}

```

Nothing really happens after I hit the submit button. I get sent back to the form as if nothing happened.

# Answer
A form submission handler doesn't use `echo` to output its result. You need to use a render array to render the result, such as with the following code. I assume `usersearch_form()` is the form builder function.

```
function usersearch_form($form, &$form_state) {
  // Add the form elements.

  if (!empty($form_state['username'])) {
    $form['username'] = array(
      '#markup' => t('The username is %username', array('%username' => $form_state['username']))
    );
  }

  return $form;
}

function usersearch_form_submit($form, &$form_state) {
  $username = db_query('SELECT name FROM users WHERE uid = :uid', array(':uid' => $form_state['values']['uid']))->fetchField();

  $form_state['username'] = $username;
  $form_state['rebuild'] =  TRUE;
}

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Modify the visibility of a form field label with #label_display attribute
In D7, I am trying to "hide" a field label through form\_alter:

```
 case 'postal_code_node_form':

   // Set fields as not required
    $form['title']['#required'] = FALSE;
    $form['body']['#required'] =  FALSE;

    // Add css to hide fields.
    $form['body']['#attributes']  = array('style' => 'display:none');
    $form['title']['#attributes'] = array('style' => 'display:none;');

    $form['body']['#label_display']  = 'hidden';
    $form['title']['#label_display'] = 'hidden';

    break;

```

Unfortunately, the label is still displayed. I could do it through CSS or JavaScript, but I would prefer doing this through `hook_form_alter()`, so all form modifications are at the same place.

# Answer
> 4 votes
I know this is over a year old, but completely removing the form labels in this way is probably not a good idea in terms of accessibility.

Instead, take a look at #title\_display defined by the FormAPI. FieldAPI has something very similar called #label\_display.

# Answer
> 1 votes
Try:

```
unset($form['title']['#title']);
unset($form['body']['und'][0]['#title']);

```

you can use dpm($form); to find labels in the form array.

I was using CSS before and I'll go the hook\_form\_alter or hook\_form\_id\_alter route as well.

---
Tags: 7, hooks
---


title: Grouping items arbitrarily in Views

text:
# Question
Title: Grouping items arbitrarily in Views
I have a taxonomy vocabulary with 4 terms. One of the content types has a term reference field to tag a node with a single term from that vocabulary. Now, I want to have Views (3.5) generate a navigation block for me which would list the terms in the following way: skip item 4 and merge item 2 & 3 into a custom item labeled, say "Item 2 & 3", as in:

```
Item 1
Item 2 & 3  [linked accordingly: taxonomy/term/2+3]

```

Of course, with eventually 2 items in a block, I could do that statically, I know. However the vocabulary may grow and would like to have a scalable, dynamic solution. Hence my question: is that possible?

# Answer
I think the easier and simpler solution would be to create a custom block from your custom module using hook\_block\_info and hook\_block\_view. By using these hooks, your block will be listed in the block administration page - **admin/structure/block**.

```
<?php
    /*
     * Implementation of hook_block_info()
    */
    function mymodule_block_info() {
        $blocks['yourblock'] = array(
        'info' => t('Your Module Name'),
        'cache' => DRUPAL_NO_CACHE
        );
        return $blocks;
    }
    /*
     * Implementation of hook_block_view()
    */
    function mymodule_block_view($delta = '') {
        $block = array(); # Declare array

        switch ($delta) {
            case 'yourblock' :
                // Block View
                $block['subject'] = 'Your Block Title';
                $block['content'] = _mymodule_taxonomy_content();
            }
        }
        return $block;
    }
    /*
     * Create block content as you need
    */
    function _mymodule_taxonomy_content( ) {
        $result = $query = db_select('taxonomy_term_data', 't')
                            ->join('taxonomy_vocabulary', 'v', 't.vid = v.vid')
                            ->condition('v.machine_name', 'your_tag_machine_name')
                            ->orderBy('t.tid')
                            ->execute();
        $content = '';
        foreach ($result as $term) {
            // you now have $term['vid'], $term['name'], etc. here
            // loop and build conditions here to suit your need
            // Item 1
            // Item 2 & 3  [linked accordingly: taxonomy/term/2+3]
            // For example,
            // $content .= l($term['name'], 'taxonomy/term/'.$term['vid']);
            // This is up to you.
        }

        return $content;
    }

```
> 1 votes

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


title: creating users form in drupal 7

text:
# Question
Title: creating users form in drupal 7
What is the easiest way to prepare separate admin panels for creating users of different roles/profiles e.g. 'add editor', 'add client', 'add subscriber' etc. that will have separate set of fields?

# Answer
> 1 votes
If you are familiar with drupal module development, I would recommend to write custom code. You may have 3 user roles - editor, client and subscriber. You can create user fields at **admin/config/people/accounts/fields**, but you cannot have separate set of fields by role. You can manage (hide/show) those fields upon user role selection from your custom module.

Please check this answer.

---
Tags: 7, forms, users
---


# Question
Title: Views: Table rows containing multiple nodes by taxonomy tag
How do I build a staff directory table that displays everyone assigned to a particular assignment? I'm using taxonomy for staff titles and staff assignments.

So in a simple example:

```
Staff1
- Title1
- Assignment1,Assignment2

Staff2
- Title2
- Assignment1

Staff3
- Title3
- Assignment1,Assignment2

Staff4
- Title2
- Assignment2

```

Table should be:

```
| Assignment  | Title1 | Title2 | Title3 |
------------------------------------------
| Assignment1 | Staff1 | Staff2 | Staff3 |
| Assignment2 | Staff1 | Staff4 | Staff3 |

```

# Answer
I ended up using Views Field View, which allows you to implement a separate view's output per row based on a particular field. Definitely resource intensive. Definitely less than ideal, but it works.
> 1 votes

# Answer
Here's what you can do to get quite close to the display you want. I'm assuming that your 'Staff1', 'Staff2' etc are user accounts. If you have a content type 'Staff' and your 'Staff1', 'Staff2' etc are nodes, the following could still be done, but some of the actual choices would be different. You didn't specify, so I'll assume they are actual user accounts.

Create a new view, but on the first page, make sure to select that this will be a listing of '**Taxonomy terms**' and go ahead and select the exact vocabulary they should be pulled from (something like 'Assignment' in your case):

Under the 'Advanced' section, add a 'Relationship' to your view. If it is indeed user profiles that these terms are attached to, select the '**Taxonomy term: User using** ' relationship. When configuring the relationship, you can select that you want that relationship to be required, if you want to only display users who have an assignment or you can leave it as unrequired if you also want to have a list of all users without an assignment as a group! This will be 'Taxonomy term: Node using ...' if you have a content type for Staff.

Finally, just add 'User: Name' to your view and in the table settings (under 'Format'), select to Group By your 'Assignment'. I'd also then check the 'Exclude from display' checkbox for the 'Assignment' term because it's a little redundant to display it as a column if you're already grouping by it.

In any case... that'll get you pretty close, though you can certainly do some extra css-ing to get it looking prettier.

Hope this helps and at least sets you on the right track...
> 0 votes

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


# Question
Title: JSONP requests not working in REST server
This is related to a bug report I filed just moments ago. If there's someone who has successfully used the REST server in the Services module with JSONP requests (cross-domain), I'd be happy to hear about it.

I'm currently trying to get cross-domain JSONP requests in services working. However, it seems that I'm out of luck. I have created a sandbox Drupal installation with just the service (and dependent) modules installed. The endpoint for testing is setup as follows:

* name: `api`
* server: `REST`
* debug: `disabled`
* authentication: `session`

The REST server is setup as follows:

* response formatters: `json`, `jsonp`
* request parsing: `application/json`, `application/x-www-form-urlencoded`, `multipart/form-data`

All resources provided by default are turned on. What I'm trying to achieve now is to get the user logged in, in order to be able to access other, permission based ressources such as node etc.

The test request is as follows:

* url and params: `http://d7.sandbox/api/user/login.json?callback=test&username=test&password=test`
* http header `Content-Type: application/json`

The response returns a 401 HTTP header and the following message:

`401 (Unauthorized: Access denied for user anonymous)`

It seems that this is not the desired behavior. JSON requests (e.g. a POST request to `api/user/login.json`) work fine. However, these cannot be used for applications running on other domains or devices to retrieve data from Drupal over the REST server.

Any ideas?

P.S. I went through the tests in the services package. It seems that tests for the JSONP functionality are missing as well.

# Answer
Try POST method instead of GET. Drupal won't allow authentication through GET method due to security reason.
> 2 votes

---
Tags: services, 8
---


title: Import currency type with Feeds import

text:
# Question
Title: Import currency type with Feeds import
Is there a way to import a currency type when doing a Feeds import? I have tried using the Feeds Tamper add on and am currently looking at this solution. It seems that I am trying to reinvent the wheel :) I have created a cck field that was called "price" as a text field and it worked beautifully. I created this as a currency field and the new "price" currency field doesn't show up as an option to map to on the mapper UI. I exported the Feed Import and added the field manually and then imported it back in. When I run the import it doesn't bring over the value that is mapped.

# Answer
> 0 votes
I believe I found a fairly hacky answer for now. In feeds/mappers/content.inc I modified the function **content\_feeds\_set\_target** after I added the *money* type to the array of included field types in line 18

```
function content_feeds_set_target($node, $target, $value) {

  $field = isset($node->$target) ? $node->$target : array();

  // Handle multiple value fields.
  if (is_array($value)) {
    $i = 0;
    foreach ($value as $v) {
      if (!is_array($v) && !is_object($v)) {
        $field[$i]['value'] = $v;
      }
      $i++;
    }
  }
  else {
    $field[0]['value'] = $value;
    //added these two lines to take care of the Money field
    $field[0]['amount'] = $value;
    $field[0]['currency'] = 'USD';
  }

  $node->$target = $field;
}

```

*I know that this isn't the way to develop in Drupal and most likely I need to set up another content type or something along that line but this helped me (who am a complete noob to Drupal) to get started importing the price field.*

---
Tags: entities, feeds
---


title: Form submit hook not executing

text:
# Question
Title: Form submit hook not executing
In a drupal 6 custom module I built, I have a menu callback which contains this:

```
function mymodule_register_confirmation() {
  return drupal_get_form('mymodule_newsletter_form');
}

```

I have the function that returns the form:

```
function mymodule_newsletter_form(&$form_state) {
  $form = array();

  $form['logo'] = array(
    '#type' => 'markup',
    '#value' => '<div class="logo-header">',
  );

  ...

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );

  ...

  return $form;
}

```

I also built the function for the submit hook of newsletter form:

```
function mymodule_newsletter_form_submit($form, &$form_state) {
    die('I am in the submit hook!!');
}

```

The page shows as expected and contains the newsletter form exactly as I want. However, when I click the submit button, it goes to the action of the form (as expected) but the submit hook I built never executes. I even tried adding the following to the function that returns the form:

```
$form['submit']['#executes_submit_callback'] = TRUE;
$form['#submit'][] = 'mymodule_newsletter_form_submit';

```

What am I doing wrong?

Thanks in advance.

# Answer
> 1 votes
Ahhhh, found the problem!

I had to specify manually a redirect to the form:

```
$form['#redirect'] = ''; // Redirects to the home page

```

This way the validate and submit hooks are called appropriately and then it redirects to the home page.

Thank you all for all your replies. I appreciate it.

Cheers.

# Answer
> 0 votes
Without the additional `$form['#submit'][] = 'mymodule_newsletter_form_submit';`, your code works just fine as is (pasted into a clean d6 install). There has to be something else going on that's preventing the submit handler from executing.

---
Tags: forms
---


# Question
Title: Where do I find a list of commonly used features?
I've been searching around for some useful features. I would assume that there are some common features that people use all the time, like an image gallery. Is there a place where people contribute these? I have searched Google and drupal.org but can't seem to find anything.

# Answer
> 3 votes
It looks like the Debut Project collection might be up your alley. From the project description:

> Debut is a set of baseline Drupal features available as apps and designed to work independently yet integrate seamlessly together.

# Answer
> 0 votes
This isn't an answer per-se, more a useful suggestion that's too long for a comment :)

I would propose that your best option would be to create a Github (for example) account, start generating Features out of projects that you've been part of before, and pop them into some individual repositories. That way you know what the Features are capable of. Trust me, after a while you will build up a personal repository containing Features you'd never even have thought you'd need.

On another note, you should definitely take a look at Apps (and the Open App Standard) to get an idea of the direction some Drupal distributions are taking:

> First there were modules, then there were Features, and now there are Apps. Apps is the next generation of extensibility and interoperability for Drupal. They provide a much better user experience of extending your Drupal site by providing facilities to download modules and all of their dependencies in one easy step.

Apps are pretty much a way of distributing Features from within a Drupal installation.

**EDIT**

I forgot to add this re: Apps. LevelTen Apps.

> Provides an Apps connector to the LevelTen Apps server.

If you like the idea of Apps, then this is actually a pretty good answer to your question ;-)

---
Tags: features
---


# Question
Title: Form Submit - Populate Title Before Validation
I have no idea why I cannot find an answer to this. I've been able to do this with other fields except the 'title' field.

I have a form which I need to automatically populate the title field. I don't want the user to populate it, so I'm hiding it by wrapping it in a that's hidden.

I used hook\_form\_alter() to add a callback function to the form's #submit array, but those functions are called after the validation. This would result in an error telling the user to enter a title.

Now I'm trying to use hook\_form\_alter and adding a validation callback function to the BEGINNING of the array like so:

```
function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    //Hide the title field
    $form['title']['#prefix'] = '<div style="display: none;">';
    $form['title']['#suffix'] = '</div>';
    //Callback function to execute before validation
    array_unshift($form['#validate'], '_previous_meetings_set_meeting_title');
}

```

Here is the callback function that is being called but NOT working:

```
function _previous_meetings_set_meeting_title(&$form, &$form_state)
{
    $form_state['values']['title'] = 'SOMETHING';
}

```

What am I doing wrong? Can I set values in a validation callback? Is there a right approach to this?

Thanks!

# Answer
If you use `#prefix` and `#suffix` with `display:none`, it is hidden in display, but submitted and will be validated for required.
Try to use `#required = FALSE` and `#type = 'hidden'` and then set title in your submit handler.

```
function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    // Hide the title field
    $form['title']['#required'] = FALSE;
    $form['title']['#type'] = 'hidden';
    // Callback function to execute before validation
    array_unshift($form['#submit'], '_previous_meetings_set_meeting_title');

}

```

And you could also use Automatic Nodetitles with which you may use token replacement.
> 3 votes

# Answer
Nevermind...got it. My solution:

```
function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
     $form['title']['#required'] = FALSE;
     $form['title']['#prefix'] = '<div style="display: none;">';
     $form['title']['#suffix'] = '</div>';
     $form['#submit'][] = '_previous_meetings_set_meeting_title';
}

function _previous_meetings_set_meeting_title(&$form, &$form_state)
{
    $form_state['values']['title'] = 'SOMETHING';
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Can I control which database Drupal uses for certain data?
It is of course possible in a custom modules to use two different databases (and I mean different *databases* not different RDBMSs!), but is there a way to use two different databases, and then force Drupal to keep certain data in one and other data in the other?

For instance, keep nodes (and closely related tables) in one, and all site configuration in another. (Perhaps, while sorting it out, it might be useful to have a third as the default. That way everything that's not sorted into either the content or the configuration database would remain in the default until you decided where it best fit.)

How can this be done, without major hacking of Drupal's core?

# Answer
> 3 votes
If it's not possible at the Drupal level, this *might* be possible at the MySQL level using the FEDERATED storage engine. This is a thoroughly untested solution, however, and it might not play nice with Drupal.

# Answer
> 2 votes
Sadly, without core hacking (and a lot of it), you can't accomplish this. And, even if you could, other third party modules would expect tables to be in the default database.

I suppose, an 'easy' trick would be to put a switch in the db\_query function and base it on the table name. But that is still a hack and I have a feeling will cause more trouble than it is worth.

---
Tags: 7, database
---


title: Drupal view field

text:
# Question
Title: Drupal view field
In Drupal, I would like to display some user related nodes on their "My Account" page. I would like to do so by creating a View that i would add as a field on the user entity (through admin/config/people/accounts/display). I could use Computed Field in order to load and render the view but that is not very convenient as it requires me to write PHP code.

In short, is there a module that allows to add dummy fields containing a view in the "manage display" sections of entities?

Thanks for your help.

# Answer
> 1 votes
There is exactly such a module ViewField.

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.
>
> Features Author chooses a view and display from a list. View arguments are supplied through tokens. Administrators may restrict which views may be assigned. Administrators may supply a common value that will be used for all entities in a content type.

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