# Question
Title: A nice way to build a related content algorithm
I am making a custom D7 module which has a block that lists related nodes of the current node you're viewing. The relation is determined by Taxonomy terms (from 1 vocab). The complication is that the related nodes need to be ordered by how many tags are matched in descending order.

How can you order nodes by matching tags? I have an idea of how to select nodes with matching tags, but have no clue as to how to order these by the number of matching tags. Any suggestions? Do it in SQL or in PHP?

Are there any modules that implement such functionality?

### Simple case study for clarity

I have 2 content types: **basic\_page**, **article**

Both of these content types have a same term reference field: **field\_tags**

When someone opens a `basic_page` node that has been tagged with Tag A, Tag B and Tag C, I want to show `article` nodes that have been tagged with Tag A, Tag B and Tag C. But these `article` nodes need to be ordered by 'relevancy'. For example: the `article` nodes with all 3 tags matched must be at the top, and `article` nodes with 2 matching tags comes next, then the ones with 1 matching tag.

# Answer
This was what I ended up writing to select nodes:

```
$query = db_select('node', 'n');
$query->addField('n', 'nid');
$query->addExpression('COUNT(n.nid)', 'ncount');
$query->innerJoin('taxonomy_index', 'ti', 'n.nid = ti.nid');
$query->condition('ti.tid', $tids, 'IN');
$query->condition('n.type', $types, 'IN');
$query->condition('n.nid', $node->nid, '<>'); // Exclude current node
$query->condition('n.status', 1); // Published
$query->condition(
  db_or()->condition('n.language', 'und')
         ->condition('n.language', $node->language)
);
$query->groupBy('n.nid');
$query->groupBy('n.title');
$query->groupBy('n.created');
$query->orderBy('ncount', 'DESC');
$query->range(0, 10);

$results = $query->execute();

```

Kudos to Similar by Terms module, as I copied most of it from there. The magic happens when you order by `ncount` field.
> 3 votes

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


# Question
Title: Why are hooks (except hook_help) not working?
```
<?php
function webformta_init() {
    dsm('hello world');
}

```

does absolutely nothing.

```
<?php
   dsm('hello world');

```

sets an alert message with the text "hello world".

I've tried wrapping this in several hooks. Hook\_load, hook\_node\_load, you name it.

But somehow, oddly, hook\_help seems to be working.

```
function webformta_help($path, $arg) {
  switch ($path) {
    case "admin/help#webformta":
      return '<p>'.  t("Grades quizzes like a TA. Works with Webform.") .'</p>';
      break;
  }
}

```

creates a nice little help link in the module list and outputs the text and everything.

What did I screw up?

# Answer
> 4 votes
You need to clear the cache after adding new hooks.

---
Tags: hooks
---


# Question
Title: How do I get a count of comments by querying the database table?
I'm migrating my Drupal forum and trying to export MySQL base as CSV. Among other things, I need to get comment counts.

How can I achieve it?

To be clear, this is what I have up to now:

```
SELECT node.nid, forum.tid, node_revisions.uid, node_revisions.title, node_revisions.body
FROM node, forum, node_revisions
WHERE node.vid=node_revisions.vid AND node_revisions.vid=forum.vid AND type='forum'

```

And I also would like to get comment counts for every node.

To be even more clear, this is what I would like to get.

```
| nid  | taxonomy id | author   | title      |  body       |comments count|
|------|-------------|----------|------------|-------------|--------------|
| 3    | 2           | 1        | Topic 1    | Topic body..|(I need this!)|
| 7    | 3           | 3        | Topic 2    | Topic body..|(I need this!)|
| 2068 | 2           | 287      | Topic 3    | Topic body..|(I need this!)|
| 12738| 4           | 4        | Topic 4    | Topic body..|(I need this!)|

```

The last column is what I need to get.

# Answer
In Drupal 6, the Comment module defines a database table ("node\_comment\_statistics") that contains the number of comments per node. See comment\_schema().

I would use the following query.

```
SELECT node.nid, forum.tid, node_revisions.uid, node_revisions.title, node_revisions.body, node_comment_statistics.comment_count
FROM node
  INNER JOIN forum ON node_revisions.vid = forum.vid
  INNER JOIN node_revisions ON node.vid = node_revisions.vid
  INNER JOIN node_comment_statistics ON node.nid = node_comment_statistics.nid
WHERE node.type = 'forum'

```
> 0 votes

# Answer
I think you can do it using the following query:

```
SELECT count(comments.cid), node.nid
FROM node
INNER JOIN comments on node.nid = comments.nid
WHERE node.type='forum'
GROUP BY node.nid

```
> 1 votes

---
Tags: database
---


title: Restore blocks on Drupal 7

text:
# Question
Title: Restore blocks on Drupal 7
How can I restore the original position (order and initial regions) of blocks on Drupal 7?

I need to make a button that you can restore the block position on Drupal 7. What function or table can be used?

# Answer
The information about the blocks are saved in the "block" table. The block information is saved in the admin form handled by block\_admin\_display\_form() using the following code.

```
  foreach ($blocks as $i => $block) {
    $key = $block['module'] . '_' . $block['delta'];
    $form['blocks'][$key]['module'] = array(
      '#type' => 'value',
      '#value' => $block['module'],
    );
    $form['blocks'][$key]['delta'] = array(
      '#type' => 'value',
      '#value' => $block['delta'],
    );
    $form['blocks'][$key]['info'] = array(
      '#markup' => check_plain($block['info']),
    );
    $form['blocks'][$key]['theme'] = array(
      '#type' => 'hidden',
      '#value' => $theme,
    );
    $form['blocks'][$key]['weight'] = array(
      '#type' => 'weight',
      '#default_value' => $block['weight'],
      '#delta' => $weight_delta,
      '#title_display' => 'invisible',
      '#title' => t('Weight for @block block', array('@block' => $block['info'])),
    );
    $form['blocks'][$key]['region'] = array(
      '#type' => 'select',
      '#default_value' => $block['region'] != BLOCK_REGION_NONE ? $block['region'] : NULL,
      '#empty_value' => BLOCK_REGION_NONE,
      '#title_display' => 'invisible',
      '#title' => t('Region for @block block', array('@block' => $block['info'])),
      '#options' => $block_regions,
    );
    $form['blocks'][$key]['configure'] = array(
      '#type' => 'link',
      '#title' => t('configure'),
      '#href' => 'admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure',
    );
    if ($block['module'] == 'block') {
      $form['blocks'][$key]['delete'] = array(
        '#type' => 'link',
        '#title' => t('delete'),
        '#href' => 'admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/delete',
      );
    }
  }

```

Using `$form_state['values']['blocks'][$key]['module']`, and `$form_state['values'][$key]['delta']`, you can find the block information from that table, and set the form fields to the values found in the database. In the submission handler for that button, you should also set `$form_state['#rebuild']` to `TRUE` to rebuild the form with the restored values.
> 2 votes

---
Tags: 7, blocks
---


# Question
Title: How to export format settings (label, weight, etc) for body field, image field, and tags field
I'm trying to export my layout settings that I did in Display Suite for my article content type full content view. All my settings for various fields (label and order) do take except the image, body, and tag fields. For example I change the label for the body field to hidden, export, and clear my db but when I go back to look it shows it as 'above'. I've tried to go into the exported code for display suite itself and insert in a 'label' =\> 'hidden' into the array also but that doesn't work either.

The order issue is where the tags field always show up before the body field. I've even checked the ds\_layout\_settings\_info() function and the weight numbering of the array looks correct.

Why is it that only those three fields won't export correctly? Someone said that those specific settings are in core/field api fields but I can't find what to export in Features.

# Answer
> 1 votes
I figured what I was doing wrong. Since I was working with Features for some reason the Article Content Type originally got exported out into another module and was clashing with mine.

---
Tags: entities, features, display-suite, importing-exporting
---


title: Access callback evaluated on every page

text:
# Question
Title: Access callback evaluated on every page
I have a custom module with a menu entry that has a page callback and a access callback. However, every time I visit ***any*** page, the access callback is evaluated. Could somebody enlighten me?

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

  $items['foo'] = array(
    'page callback' => 'foo',
    'access callback' => 'foo_access_callback',
  );

  return $items;
}

function foo() {
  //...
}

function foo_access_callback() {
  error_log('This gets evaluated on every page.');
  return TRUE;
}

```

# Answer
Something just dawned on me...if you have a menu on the page that links to the '/foo' page, Drupal will query the access callback to find out if the menu link can be shown.

Since you're not providing a `type` in your menu item, it will default to `MENU_NORMAL_ITEM` which will place it in the site's Navigation menu.

I would guess that's what's causing the function to be run at least once on every front end page, but not for the admin pages (where you probably won't have the same menus).

It's definitely what was causing the issue on the test installation I just set up for this.
> 2 votes

---
Tags: 7, routes
---


title: How do I link an image to a given URL?

text:
# Question
Title: How do I link an image to a given URL?
I'm using Panels to generate my front page. In one of the panes in my panel layout, I want to have an image which is linked to a given URL. The image and URL are going to be managed by my users.

I've been told that the Link module will give me a field type for URLs., and the Link Image Formatter module will let me link images to URLs; but I can't find any documentation on how to actually use the link image formatter. (EDIT: It turns out the Link Image Formatter wasn't about making href links, but just including images from a different domain.. or something, I'm confused.)

I've tried creating a content type with an image field, and a link field, but I can't find any way to connect them, or any way to associate an image with the link field.

EDIT: The URL may be internal to the drupal site or it may be external. These image/link combinations will be created and managed by the user through drupal. There may be 4 of them on the front page, but I may need to use them more later on throughout the site. They aren't unique to each user, I'll only have one admin user who will be posting all of the content on the site.

I want the user to add a piece of content. They'll upload an image and they'll define the URL they want that image to link to. Then in one of my Views/blocks, I can select that content type and show it in a certain region. It'll just show the image, but if a user clicks on the image, it'll take them to the specified URL which may be external to the site.

This seems like a wheel that should already have been invented, but I'm having trouble finding them.

How can I achieve this?

EDIT: I figured out what I was doing wrong... I think the person who suggested the Link Image Formatter module to me may have hastily picked the wrong url when they sent it to me and really meant to send the Link Image FIELD module which does exactly what I expected.

# Answer
I figured out what I was doing wrong... I think the person who suggested the Link Image Formatter module to me may have hastily picked the wrong url when they sent it to me and really meant to send the Link Image FIELD module which does exactly what I expected.

Link Image Field module is the right one. It let's you create a field in your content type of type "Link Image" and when you add content and upload an image, it asks you for the URL you want to link it to. I knew this had to have been solved before me, I was just using the wrong, but similarly named, module.
> 2 votes

# Answer
you can load a image from a node.

```
 $prev_node = node_load($prev->nid);
    $image = field_get_items('node', $prev_node, 'field_image');
     $img = field_view_value('node', $prev_node, 'field_image', $image[0], array(
      'type' => 'image',
      'settings' => array(
      'image_style' => 'thumbnail',
      'image_link' => 'content',
     ),
   ));

```

then if you get the image, linking image to a certain url can be easily done by

```
 $options = array(
            'html' => TRUE,
            'attributes' => array(
                'title' => $prev_node->title
            )
 );
 $output = l($img, "your url", $options);
 print render($output);

```
> 3 votes

---
Tags: 7, media, navigation
---


# Question
Title: How can I display a change password form on its own?
I have a need to place a user's password reset form in areas outside the context of the user edit page.

This Change Password module looked promising; however, it is only available for drupal 6 and only a dev snapshot is available.

I could use hook\_form\_alter to hide the fields on the edit user form that are not related to the user's password, but I would prefer not to do that if at all possible.

I'm hopping this functionality exists somewhere already.

Thanks in advance.

# Answer
> 27 votes
I couldn't find anything out there already and it sounded like a handy thing to have, so here's a small module providing a block with a change password form:

File: change\_password.info

```
name = Change Password
description = Provides a block containing a form for the current user to change their password.
core = 7.x

```

File: change\_password.module

```
<?php

/**
 * Implements hook_block_info().
 */
function change_password_block_info() {
  return array(
    'change_password_form' => array(
      'info' => t('Change Password Form')
    )
  );
}

/**
 * Implements hook_block_view().
 */
function change_password_block_view($delta = '') {
  $block = array();
  // Only show the block for a logged-in user.
  if ($delta == 'change_password_form' && user_is_logged_in()) {
    $block['subject'] = t('Change Password');
    $block['content'] = drupal_get_form('change_password_form');
  }
  return $block;
}

/**
 * Password change form.
 */
function change_password_form($form, &$form_state) {
  // Sanity check
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }

  // Get the currently logged in user object.
  $form['#account'] = $GLOBALS['user'];

  // Textfield cor current password confirmation.
  $form['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE
  );

  // Password confirm field.
  $form['account']['pass'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#title' => t('New Password'),
    '#required' => TRUE
  );

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

  return $form;
}

/**
 * Validate handler for change_password_form().
 */
function change_password_form_validate(&$form, &$form_state) {
  // Make sure the password functions are present.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

  // Make sure the provided current password is valid for this account.
  if (!user_check_password($form_state['values']['current_pass'], $form['#account'])) {
    form_set_error('current_pass', t('The current password you provided is incorrect.'));
  }
}

 /**
 * Submit handler for change_password_form().
 */
function change_password_form_submit(&$form, &$form_state) {
  // Set up the edit array to pass to user_save()
  $edit = array('pass' => $form_state['values']['pass']);

  // Save the account with the new password.
  user_save($form['#account'], $edit);

  // Inform the user.
  drupal_set_message(t('Your password has been changed.'));
}

```

It's (lightly) tested and works, but you might want to give it a once-over for your own peace of mind.

**Update** I've chucked it up as a sandbox project in case anyone's interested.

# Answer
> 7 votes
Here's another approach.

In my example, I render the built-in `user_profile_form()`, and simply unset the unnecessary fields. It's good because this way Drupal's own validation functions get called, the JavaScript-based password strength AND password matching indicator also gets rendered, and the field labels and descriptions are the same as on the user edit form (except that here I took out the e-mail changing text), but you can also change them, if you wish.

The result will look like this:

(Full screen)

This form will be visible at `example.com/change-password` path (of course, `example.com` should be substituted to your domain), and I'll also define a block for it.

```
/**
 * Implements hook_menu().
 */
function YOURMODULENAME_menu() {
    $items = array();

    $items['change-password'] = array(
      'title' => t('Change password'),
      'description' => t('You can change your password here.'),
      'page callback' => 'YOURMODULENAME_render_user_pass_change_form',
      'access arguments' => array('access content'),
    );

    return $items;
}

/**
 * Render the password changing form with the usage of Drupal's built-in user_profile_form
 *
 * @global type $user
 * @return array The rendered form array for changing password
 */
function YOURMODULENAME_render_user_pass_change_form() {

    global $user;

    if (!user_is_logged_in()) {
        drupal_access_denied();
    }

    module_load_include('inc', 'user', 'user.pages');
    $form = drupal_get_form('user_profile_form', $user);

    $request_new = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
    $current_pass_description = t('Enter your current password to change the %pass. !request_new.', array('%pass' => t('Password'), '!request_new' => $request_new));

    $form['account']['current_pass']['#description'] = $current_pass_description;

    unset(
      $form['account']['name'],
      $form['account']['mail'],
      $form['account']['status'],
      $form['account']['roles'],
      $form['locale'],
      $form['l10n_client'],
      $form['picture'],
      $form['overlay_control'],
      $form['contact'],
      $form['timezone'],
      $form['ckeditor'],
      $form['metatags'],
      $form['redirect']
      );

    return $form;
}

define('PASSWORD_CHANGING_BLOCK', 'password_changing_block');

/**
 * Implements hook_block_info().
 */
function YOURMODULENAME_block_info() {

    $blocks = array();

    $blocks[PASSWORD_CHANGING_BLOCK] = array(
      'info' => t('Block for changing password'), //The name that will appear in the block list.
      'cache' => DRUPAL_CACHE_GLOBAL, // The block is the same for every user on every page where it is visible.
    );

    return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function YOURMODULENAME_block_view($delta = '') {

    switch ($delta) {
        case PASSWORD_CHANGING_BLOCK :
            if(user_is_logged_in()){
                $block['subject'] = t('Change Password');
                $block['content'] = drupal_get_form('YOURMODULENAME_render_user_pass_change_form');
            }
            break;
    }
    return $block;
}

```

Of course, substitute `YOURMODULENAME` with your own module's name (even near `'page callback'` and when calling `drupal_get_form`)! You can also unset other fields if necessary (e.g. more fields are rendered via another module).
Clear the cache after putting it in your code.

After this, You can simply render this form by calling `drupal_get_form('YOURMODULENAME_render_user_pass_change_form');`.

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


# Question
Title: How to create a menu navigation on a Views page that uses contextual filters?
I have a *projects* content type and I want there to be a menu for each project that would have *Project Overview*, *Project Details* & *Team Members*.

So in Views I created a page at `projects/` which would be the overview page that filters based on project title.

Then I have a page at `projects/%/details`, and another at `projects/%/people`.

So how would I either create a menu that I could put in the sidebar or somewhere that would work for any project, or maybe use tabs instead? Whichever is fine, but if you could teach me how to do both that would be cool.

I tried using the menu settings under *Page Settings* in Views, but I couldn't get it to work.

# Answer
Open the view where you had created the pages at **projects/%/details** or **projects/%/people**.

Under page settings where you had the path filled, add these additional settings to create a **Menu tab** or a **Contextual link**.

Go to **Menu** and select **Menu tab** as the type and fill in the title. If you want the link to be present as a contextual link, check the box which says context.

You can also set access permissions on who can see this tab depending upon the permission type you had selected.
> 1 votes

---
Tags: views, routes
---


# Question
Title: Dropdown menu of node titles that are made by a view
I'm trying to create a dropdown menu that is a list of titles created by a view.

So I've made a view that creates a list of titles of a content type. I would like that list of titles to be in a dropdown menu.

I am using Superfish now, but I am not fully committed to it. If you can suggest a menu that will make this work I'm open to that.

I thought Menu Views would be an easy fix combined with Superfish. Menu Views has this to say

> By design, this module only provides basic HTML structure for inserting a view into the menu system. It does not actually style your \[mega-\]menu. If no styling exists in your theme or is not provided by a contributed module, the view will appear next to your menu item (which can often be a little confusing at first). It is up to the theme or contributed module to actually style the view to appear inside your menu. If the contributed theme or module implements drop down menus, using CSS or JavaScript, a new child selector (li \> .view) must be included. The view can then be styled appropriately from there.

I'm not sure where to start with the child selector.

Any advice on how to get the dropdown menu to display the node titles? Feel free to recommend any other modules that may help

# Answer
I don't know if or how the Superfish module integrates with Menu Views. Off the top of my head I kind of suspect it doesn't...

The simplest solution is to use CSS to hide the view except during the parent's :hover state. You can pick up a simple js to make that function in IE7 and below. There are of course plenty of other, mostly javascript or jQuery-based, solutions.
> 0 votes

---
Tags: views, navigation
---


title: Correct way to add a tweet button?

text:
# Question
Title: Correct way to add a tweet button?
I'm trying to add a tweet button to my node.tpl.php in Drupal 6 - https://dev.twitter.com/docs/tweet-button.

I literally place the html+javascript within node.tpl like so:

```
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script><

```

The result is a flickering button every time I refresh, so I'm thinking the javascript is loading incorrectly?

Ideally, I'd like to load the javascript within page.tpl.php, and ensure that it applies to node.tpl, but it doesn't appear to be working. I've also tried loading it using drupal\_add\_js within template.php various preprocessor methods.

I rather not use any of the social media modules - such as AddToAny, ShareThis, or ServiceLinks - partly because I feel this should be cut and dry w/o module dependency.

So I guess my question is - what is the best way to load that twitter javascript code within node.tpl to avoid the flickering button?

# Answer
> 2 votes
Do not place the `<script>` tag in node.tpl.php because it will repeat if multiple nodes are arranged to appear in a single page.

Use following code to add js in page and call this function in hook\_init() or in your page's callback function.

```
drupal_add_js('<script>...</script>',array(
  'type' => 'inline',
  'scope' => 'footer'
));

```

---
Tags: nodes, javascript, theming, social-network
---


title: Filter/sort content displays/listings

text:
# Question
Title: Filter/sort content displays/listings
I need to implement the functionality of sorting the content listed to the user based on attributes like alphabetically, popularity or price (ascending/descending). These attributes can also be custom. I need to have it has a widget. I don't exactly know what this functionality is called so apologies if I'm not being clear.

I also need to display text like "Displaying % of %" on top the list which, as far as I've seen, views don't do by default.

An example could be this website.

I'm using Drupal Commerce (D7).

So is there a module for this?

# Answer
Views allows you to expose sorts, but doesn't create the type of UI you are asking for by default.

What you get by default with views after clicking 'expose' at the top of your sort value is two menus, one for the value to sort by, and one for the sort direction.

The most important thing to remember here is what you get in your view's url after submitting this original exposed filter form: /myviewpath?sort\_by=XXXXX&sort\_order=XXXXX.

You can write your own custom module, do a hook\_form\_alter of the existing form, a fancy jquery widget, heck write it in Flash if you really want to, all the view cares about is you passing those two values and that those values are enabled and available for that view.

In terms of getting your own custom values available there have a look at the views sort class documentation and the view\_handler\_sort\_\* examples already provided in /views/handlers. Views argsort looks pretty interesting as well if you don't want to write your own sort handler but haven't tried that module myself yet.

For part 2 of your question this summary is already provided by views. Click on header, click on "Global Result Summary", and use the tokens provided to create your summary.
> 3 votes

---
Tags: views, nodes
---


# Question
Title: Recommend a slideshow module that can create a display from a view?
We have a design comp that looks like this:

We have a content type called `speaker`, which contains a file field that the headshot image is uploaded to. There are also several other fields, including an entity reference to another content type. What we'd like to do is be able to create a view that contains all the info we need and then have it formatted as a slideshow (where mousing over a single image brings up a div or something containing speaker name, company, etc.)

I've found several slideshow modules that are integrated with Views, but none of them seems to do quite what we need. Any suggestions?

# Answer
> 2 votes
Looks like the jCarousel module has Views support and produces a similar looking display: http://drupal.org/project/jcarousel

It is also maintained by one the top Drupal contributors.

# Answer
> 4 votes
To be honest, I have never been satisfied with any of the existing slideshow modules.

Typically, I use Views to render out the HTML I want. Sometimes I use field output, but lately I have been using node output with a custom view mode.

The I use some custom CSS and JS to make the slideshow do exactly what I want.

Normally, I wrap all of this up in a custom block.

It may sound complicated, but it usually only takes a few hours to do all of this.

# Answer
> 2 votes
I was recently pointed to Views + Views Slideshow + Views Slideshow: Galleria and I really dig it.

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


title: Extending Panels default layouts

text:
# Question
Title: Extending Panels default layouts
I'm making my first steps into Panels (yeah, shame on me I waited so long)... I immediately ran into a problem with the column-resize widget which did not want to obey. So I thought maybe there i a programmatic workaround for my need.

What I need is a 5-row layout:

```
1: 1 column
2: 3 equal columns
3: 1 column
4: 2 columns (2:1 ratio)
5: 1 column

```

How do I add a custom layout (with own icon, name and php template) so that Panels recognizes it?

# Answer
> 0 votes
Never mind. Here I found the answer

---
Tags: panels, theming
---


# Question
Title: How to access the view display's field list in row plugin options
I am trying to create a row plugin that would be similar to the plugin in date\_ical. The difference would be that it wouldnt use the entity display but the fields defined in the view, thus allowing for example to place information from related entities.
To do this I would need to setup options in the options\_form where i would select form the defined fields whih is the title and so on. Somehow i cant access the information about the defined fields. I keep searching the $this-\>view object and around, but cant find it :(. I am sure it has to be there. Please help !

# Answer
i found `$this->display->handler->get_field_labels();` in views\_plugin\_style.inc and it seems to do the trick.
> 0 votes

---
Tags: views
---


title: Naming convention for Drupal views

text:
# Question
Title: Naming convention for Drupal views
I have a view setup named `Homepage Suppliers`.

It is a jCarousel format that displays an image field which links to the content.

What I'm looking to do, is theme this using a view template to get it exactly how I want it.

I've tried using the following file names:

`views-view--homepage-suppliers.tpl.php`

`views-view-list--homepage-suppliers.tpl.php`

Do these look right?

Thanks

# Answer
Views has a nice built-in way to help you decipher which template filename(s) to use.

Open up your view in edit mode, go to the display that you're interested in, and open up the 'Advanced' tab. Right at the bottom you'll see the "Theme: Information" link. Click that, and you'll be presented with a popup that looks something like this:

Once you've decided on the right filename, create the file and populate it, then make sure to clear Drupal's theme registry caches or the changes won't get picked up.
> 8 votes

---
Tags: views, theming
---


# Question
Title: Default date field values like "today +10 hours 30 minutes"
I have a date\_field Date (ISO format) as a Pop-up calendar. I would like to have it as a default value: today 10:30 In php the

```
strtotime("today +10 hours 30 minutes")

```

serves me well. Also

```
strtotime("today 10:30 am")

```

If I put it in the "Relative default value" field, the time gets not parsed. It is always the current time.

```
strtotime("noon")

```

or

`strtotime("midnight")`

has the same effect. Bug? How to get the default date to "today 10:30 am"?

# Answer
> 1 votes
It's been fixed, YAY! http://drupal.org/node/1302212

# Answer
> 4 votes
The best way to control the default output of form elements is through the drupal Form API.

You have two scenarios:

1. If you created the form with the form api and have a date popup in your form, you can use the method described in this post to set the #default\_format of the #default\_value of the form element.
2. If you didn't create the date popup in the form element with the form api, meaning you added it as a field to an entity through site configuration, you can still make a small custom module solution. Make a custom module and implement hook\_form\_alter, find the field in question and set the #default\_value using the method mentioned in #1

# Answer
> 1 votes
This will surely work.

```
$form['date'] = array(
  '#type'=>'date_popup',
  '#date_format'=>'d-m-y',
  '#default_value' =>date('Y-m-d'),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#prefix' => '<td>',
  '#suffix' => '</td></tr></table>',
  '#size'=>20,
);

```

---
Tags: 7, datetime
---


# Question
Title: Change 'Administration theme' not working - still shows current theme for administrative tasks
I have a custom theme that works fine. I want to use D7's 'Seven' theme for administration. However, despite it being chosen already, Drupal uses my custom theme for administration and editing.

If I change themes to a Drupal default theme like Bartik, then, I can change the administration theme to whatever I want, even my custom theme, and everything works as expected.

This tells me I have something wrong with my theme. What am I missing? Are there any default drupal theme variables that I need to include to make sure that the overlay theme is indeed Seven (or whatever I choose). What could be causing my theme to disregard my Administration Theme choice and use my custom theme regardless of the setting?

note: I am trying to give 'overlay' permissions to others and want them to use the Seven theme. I forgot to mention that this works fine if I am logged in as Admin (user 1) but everyone else gets the custom theme for admin regardless of what I choose.

# Answer
> 0 votes
Toolbar - Use the Administrative toolbar is a role permission. Check there if you are having the same problem to make sure it's checked for the role you would like to be able to access the toolbar at the top of the page.

---
Tags: 7, theming
---


# Question
Title: 200 OK on every page after updating the content
i have uploaded my localhost site to online, my site was working ok at localhost, but after uploading online whenever im upadating any content it shows me this error message on every page.Please help...

OK The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, \[no address given\] and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

HTTP/1.1 200 OK Date: Fri, 25 May 2012 05:40:26 GMT Server: Apache/2.2.22 (Unix) FrontPage/5.0.2.2635 X-Powered-By: PHP/5.3.8 Expires: Sun, 19 Nov 1978 05:00:00 GMT Cache-Control: store, no-cache, must-revalidate, post-check=0, pre-check=0 Last-Modified: Fri, 25 May 2012 05:40:26 GMT Keep-Alive: timeout=5, max=399 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 5527

# Answer
> 1 votes
I found the solution: Just uncomment the line containing the `RewriteBase /` directive in the .htaccess file.

---
Tags: users
---


title: How to render field in hook_form_alter?

text:
# Question
Title: How to render field in hook_form_alter?
I am trying to show a user profile field in node form.

```
function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id){
        $form['myfield'] = array(
            '#markup' => drupal_render(field_view_field('user', $account, 'field_myfield'));
        );
}

```

`field_view_field()` is not returning any thing.

# Answer
I don't see a definition for the `$account` object anywhere in your code. You're probably missing the following lines before your call to `field_view_field()`:

```
global $user;
$account = user_load($user->uid);

```

Also, and this might sound stupid, but make sure you replace `FORM_ID` with the actual ID of your form :)
> 2 votes

# Answer
Question is, the profile field of which user? The node author, or the current user?

In both cases you need to fetch the $account you are trying to pass to field\_view\_field.

For the current user:

```
global $user;
$account = user_load($user->uid);

```

For the node author:

```
$account = user_load($form_state['node']->uid);

```
> 3 votes

---
Tags: 7, entities
---


# Question
Title: Get fields to appear in fields list, arguments list and filters list in view
I am using hook\_form\_alter and adding a extra form field to drupal node form. All works fine, but in view this field is not show up. How do i add this field?

# Answer
> 1 votes
Instead of adding form element using hook\_form\_alter use CCK field. View will not understand your custom field but a CCK fields are integrated in views.

EDIT

Please check for Tag User module.

# Answer
> 0 votes
To make you understand the difference between a **form field** and a **CCK field** in a Node form relationship:

## **Formfield**

You could add a formfield to a node form, but this would only add a `<input>` field to your form. After adding this field, you could use Drupal's Form API (Drupal.org Form API quickstart guide) to for example validate the fields, or process them in any way you see fit. To be clear, without any validation, post-processing, etc. your field will **not** be used in any way.

That being said, a form field is only interesting when you make a custom module, which needs some additional information about a node which will be created / editted.

## **CCK field** (Simply: **Fields** in Drupal 7)

You have numerous types of fields (eg. Text, number, references, file, etc...) which you can assign to different node types. For example, you could add a **imagefield** field to a node-type "Employee" to make it possible to add a picture of a employee.

I hope this clears it up a bit for you.

**edit**

I noticed you where trying to add a "user autocomplete" field? Try out the CCK User reference field, it's in the base module if you're using Drupal 6. If you're using Drupal 7 you'll need a separate module: References.

---
Tags: 6
---


# Question
Title: how to extract values of field collection using Entityfieldquery?
I have created a content type 'customer' in which I have a field collection named 'field\_group'. The field collection has 2 fields namely:

> 1. Title
> 2. Name

The Customer content type and group field collection are of entity type 'node' and the 2 fields in the group are of entity type 'field\_collection\_item'. I want to query the database to get the values of the fields in the group for this particular content type. I used to following query to get the field values of the group.

```
    $query = new EntityFieldQuery();

    $query->entityCondition('entity_type', 'field_collection_item')
          ->entityCondition('bundle', 'field_group');

    $result = $query->execute();

$nodes = entity_load('field_collection_item', array_keys($result['field_collection_item']));

```

But the above entityfieldquery retrieves all the values of entity type field\_collection\_item. But I want only the values of content type 'customers'. Can anyone tell me what's wrong with the above query?

# Answer
> 12 votes
An `EntityFieldQuery` can only refer to one type of entity, it cannot represent any relationships between entities. If the `entity_type` in your query is a `field_collection_item`, then that's the type of entity that the query will return. The `EntityFieldQuery` has no concept of the fact that your field collections are related to nodes, or anything else for that matter.

To get the entities related to the field collections you'll have to run another `EntityFieldQuery`. I haven't used field collection before but I would guess the logic would look something like this:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'customer')
  ->fieldCondition('field_name_of_collection_field', 'name_of_field_collection_column', array_keys($result['field_collection_item']));

```

There are things that need to be changed in that code (the name of your field collection field, the column name for the field collection relationship) but it should get you started.

Actual example of the two-query approach:

```
function get_species_country($id_country) {
    $inner = new EntityFieldQuery();
    $inner_r = $inner->entityCondition('entity_type', 'field_collection_item')
                     ->fieldCondition('field_species_country', 'target_id', $id_country, '=')
                     ->execute();
    if(!empty($inner_r['field_collection_item'])) {
        $keys = array_keys($inner_r['field_collection_item']);
        $query = new EntityFieldQuery();
        $species_r = $query->entityCondition('entity_type', 'node')
                      ->entityCondition('bundle', self::$bundle)
                      ->fieldCondition('field_species_countries', 'value', $keys)
                      ->execute();
        if(!empty($species_r['node'])) {
            $ret = node_load_multiple(array_keys($species_r['node']));
        }
    }
    return $ret;
}

```

In the example above:

* field\_species\_countries - Name of the field collection
* field\_species\_country - Actual field inside the field collection

**Limitations**: I think this has some limitations because the second query contains ... WHERE *field* IN (1, 2, 3 ...). For MySQL this is limited by max\_allowed\_packet

# Answer
> 0 votes
I think you'll want to use the delta\_group parameter to let EFQ know that the fields are supposed to be related. There's a good explanation in this comment on the fieldCondition documentation.

> The $delta\_group parameter allows you to group conditions together. I have always read the docs to mean that we were specifying the delta within the field itself, but this is not the case.
>
> For example, if you want to select entities based on two columns from the same field, you use a delta group to make sure that the conditions are dependent.

---
Tags: nodes, entities
---


# Question
Title: What is the specificity limit of EntityFieldQuery / fieldCondition?
* I have a webform that I want to grade, like a quiz. (No, not with the Quiz module).
* I have a content type called Answer Key with a Reference field called field\_answer\_quiz.
* Upon webform submission, I want to:

1. Look through all nodes of type Answer Key
    2. Find the one with a field\_answer\_quiz value == the current webform
    3. Use node\_load() or something to pull out content

Here's a Q&A that makes it seem possible: how to extract values of field collection using Entityfieldquery?

But here's a comment that makes it seem impossible:

> If that's what you want, then this is the correct way and `EntityField` does not help you. What `EntityFieldQuery` does is load entity IDs of entities based on their properties and fields. You could for example use it if you want to load the node(s) that has a specific version value by first loading the field collection item and then loading the node that references the field collection item. You're doing the opposite, you have the node and want the version value. **To get field values, you always need to load the entities.**

So, which is it? Is it going to be possible for me to use `EntityFieldQuery` to do this? I'd really like to avoid having to load a ton of nodes just to shuffle through them.

This is the code I am using.

```
function webformta_webform_validation_validate($validator_name, $items, $components, $rule) {
$arg = arg();
$nid = $arg[1];
dsm('The NID of the current node is '.$nid);
$query = new EntityFieldQuery;
$result = $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->propertyCondition('type', 'quiz_answer_key')
    ->fieldCondition('field_answer_quiz_nid', 'value', $nid, '=')
    ->execute();
    $results = $query->ordered_results;
  dsm($results);

```

It causes the following error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_data\_field\_answer\_quiz0.field\_answer\_quiz\_value' in 'where clause': SELECT \[...\] (error is really really long)

# Answer
Yes, it is possible.

The second question is different, what you are describing is exactly what EFQ can do.

Something like this should work:

```
->fieldCondition('field_answer_quiz', 'nid', $nid)

```

The column names in the field tables are a combination of the field name and the column name, you need to split that up like the above example.
> 4 votes

---
Tags: 7, database
---


# Question
Title: Access to install.php on existing installation
I've created an installation profile.
Once the site is created and I return to install.php I can restart the installation profile. How can the install.php file be blocked so that the Drupal already installed message is shown?
When the standard profile is used 3 variables are set in the variable table:

```

install_profile     s:8:"standard";
install_task     s:4:"done";
install_time     i:1323783143;

```
When I look at the variables table after I run my custom installation profile only one variable is set as:
```

install_task    s:23:"install_profile_modules";

```

What's the correct way to set these variables?

# Answer
> 0 votes
The issue is caused by a module that's enabled with the installation profile using the drupal\_goto function on hook\_user\_login.

This function ends the request, therefore the profile doesn't go to the page showing 'Visit your new site'. It goes to the URL provided in drupal\_goto instead and variables are not set because the function install\_finished() was never called.

---
Tags: 7, distributions
---


title: SSD drupal performance improvement

text:
# Question
Title: SSD drupal performance improvement
There are some VPS services that advertise that have SSD. Does it worth the extra money?

In a setup with varnish/nginx/php-fpm/apc/drupal/mysql, would SSD provide any significant performance improvement in drupal 7?

If yes, in which case scenarios?

# Answer
I am managing a site that gets about 1000 unique visitors a day. Not sure how big your application is, but 1000 is enough to cripple a default drupal install.

I added the standard performance optizations, apc, etc, but found that memcache by far had the best result. My pages used to take 20 seconds to load. Now pages load instantaneously. If you have not tried that, I would see if that helped first before investing in the SSDs.
> 2 votes

# Answer
faster disk writing/loading.

E.g a site frequently getting user upload content such as photo album.

Cant say worth the penny as every project is different
> 0 votes

# Answer
Only the provider is going to know if it makes an improvement. They might get a performance benefit from a switching to SSD drives. But what about providers that have very large hard drive arrays with standard 10,000 RAID drives? There's much more involved to shard disk performance than what type of hard drive is being used in the arrays.

But it's important to know that Disk Drive performance is not nearly as important as the **software they provide and support, the CPUs and memory**. The modules you listed above will provide users with a snappy Drupal site, but not all hosts support them so that is much more important.

Tips on Choosing Suitable Drupal Hosting Providers

Prices of SSD have gone down, and it makes good business sense to use them, but it's not going to be a big improvement in Drupal performance.

Varnish and APC however are wonderful ways of improving performance.
> 0 votes

# Answer
SSDs are going to be great when you have a lot of file I/O.

Unless you have this occurring in your installs of Drupal, my advice is to stick with the proven technologies for improving performance & scalability for Drupal: APC, varnish, memcached, removing unused modules, etc.

The SSD may not be worth the extra money, not yet at least. If you are looking to fork over the extra money, get more CPUs, memory, disk, etc.
> 0 votes

---
Tags: 7, performance
---


# Question
Title: Views - getting Title field from other content types via entity reference
I have two content types: `speaker` and `session`. Session has an entity reference field to speaker - when you create a session, you add references to one or more speakers.

I need to create a view of speakers and details from the speaker nodes, but also include the titles of the sessions that they're referenced on. I've added a relationship using the type `Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Content via field_speaker`, and when I go to add new fields, I can see all of the fields from the session content type EXCEPT Title. The only Content: Title that's available is the one from the speaker nodes.

What do I need to do to get the Content: Title that's on the session node?

# Answer
You should choose the one that says "Content: Title". In the next page you can choose the relationship you want this field's value to come from, i.e. your entity reference field.

e.g.
> 4 votes

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


# Question
Title: Language switcher shows me same node on switch
I am using Locale and Content Translation modules. First I created node and translated it. On content listing both have proper alias urls, everything seems to be ok.

As a guest user I see content in first language when I want to switch to translated version of current node, language switcher block gives me node in the same language (previuosly selected) and url of this node is just raw node url (node/ID). So everything is f up.

Could somebody give me any advice?

More info:

current lang is en:

language switcher links: pl (node/154) and en (en/sample)

en/sample is alias of node/154 :/

But I am sure that I have translated to "pl" node of id 154.

Lanuage codes (admin/config/regional/language): en, pl

Detections (admin/config/regional/language/configure) \- URL

# Answer
I try to solve it again and it's was Global Redirect module fault. Please use Redirect intead
> 0 votes

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


title: How to make a Role label display?

text:
# Question
Title: How to make a Role label display?
Is there an easy way to list someone's "role" sort of like a badge, next to their username?

I dont want any point system or anything like that

# Answer
I'd use Views to create a View of Users, and then you can add fields as you like.
> 0 votes

---
Tags: users
---


# Question
Title: Subnavigation doesn't show with the Bartik theme
I would like to have a menu point in my main navigation with sub-menu points.

I created a main point *+Services* with two points underneath it where I assigned the respective "Parent link".

The structure looks fine in the administrative interface, but I do not get the sub navigation points to show up or the mother point to drop down even though I selected "Show as expanded".

I placed two menu points under Services that do not show up.

Can anyone help in this matter?

# Answer
> 0 votes
Just set it as expandable in structure/menus.

---
Tags: navigation
---


# Question
Title: Jquery in ajaxed loaded content referencing incorrect node id
I have a list of nodes each with a click. The click sends a node reference argument which loads a new view using ajax. Jquery collects the node reference number via a hidden input value on the content-type-tpl.php. Likewise the nodes in the new view each have a click which sends a node reference argument which loads a new view using ajax. However while the clicks in the original view work correctly, the clicks in the newly called view do not reference the correct node. Instead of referencing the node id for the node which is clicked, the node id of the next node in the view is collected instead. Oddly when placing `<?php echo $node->nid;?>` on the content-type-tpl.php, the correct node id is echoed on the page. But sadly this is not the one sent to the view argument. So clicking any node in the the newly loaded ajaxed view, sends the id for the next node. Here's the javacript:

```
 Drupal.behaviors.ajaxlinks = function (context) {
    $('.morelink:not(.togg-processed)', context).addClass('togg-processed').each(function () {
      var myindex = $('.morelink').index($(this));
      var target = $('.newthing').eq($('.morelink').index($(this)))
      var nid = $(".mynid").eq(myindex).val();
    $(this).click(function() {
if (($('.hiddenrows').eq(myindex).is(":hidden"))
|| ($('.shownrows').eq(myindex).is(":visible")))
{
    $('.hiddenrows').eq(myindex).show();
    $('.newthing').eq(myindex).show();
      var toLoad = Drupal.settings.basePath + 'replies/' + nid;
      xhr = $.ajax({
        url: toLoad,
        success: function(data) {
        $(target).css( "height","200px" );
        $(target).html($(data));
     Drupal.attachBehaviors(context);
}
});
}
else
{
    $('.hiddenrows').eq(myindex).hide();
    $('.newthing').eq(myindex).hide();
}
    return false;

```

It's the same code so I can't see why it works differently in the newly loaded view. Can anyone spot what I am doing wrong?

# Answer
> 0 votes
Looks like Drupal.attachBehaviors should have fired on (target) instead of (context). It was refiring the script on the whole context instead of just the new ajaxed content. So I changed Drupal.attachBehaviors(context); to Drupal.attachBehaviors(target);

Now it works!

---
Tags: ajax, javascript, nodes, views
---


# Question
Title: Filter is Stripping URL with custom scheme
There are times we are using custom schemes for URLs and storing them in Drupal 6.

The href attribute values are getting stored in the db properly.

So,

```
<a href="mycustomscheme://foo/bar">

```

gets stored as it's written. However, when viewing the page the unknown scheme gets stripped so it outputs:

```
<a href="//foo/bar">

```

I've disabled all filters in the full HTML input format and have returned out of my hook\_nodeapi function in my custom module, and disabled the WYSIWIG, and still the scheme gets stripped.

Any ideas where this might be happening?

# Answer
I wouldn't recommend hacking the HTML filter in core. If you want you could copy/modify it into your own module and create your own filter, here is a link to a blog post that should help get your started.

Or you could try one of the contrib packages like Custom Filter.
> 0 votes

---
Tags: uri
---


# Question
Title: for how long is Content considered "new" by the filter criteria "Content: has new content"?
I'm trying to find out how Drupal uses the "has new content" filter criteria. I'd like to create a View that only shows the latest content on the site, but not sure what is going to be returned. 24 hours, 7 days, 30 days?

I don't see any way to set the duration, either.

# Answer
In Drupal 7, the Views module uses the NODE\_NEW\_LIMIT. If you look at the code used by the views\_handler\_filter\_history\_user\_timestamp class, which filters the new content, you will notice the following code (in views\_handler\_filter\_history\_user\_timestamp::query()).

```
  // Hey, Drupal kills old history, so nodes that haven't been updated
  // since NODE_NEW_LIMIT are bzzzzzzzt outta here!

  $limit = REQUEST_TIME - NODE_NEW_LIMIT;

  $this->ensure_my_table();
  $field = "$this->table_alias.$this->real_field";
  $node = $this->query->ensure_table('node', $this->relationship);

  $clause = '';
  $clause2 = '';
  if (module_exists('comment')) {
    $ncs = $this->query->ensure_table('node_comment_statistics', $this->relationship);
    $clause = ("OR $ncs.last_comment_timestamp > (***CURRENT_TIME*** - $limit)");
    $clause2 = "OR $field < $ncs.last_comment_timestamp";
  }

```

The same constant is used from node\_mark(), which the function that returns a value used to decide if outputting *updated*, or *new* in a list of nodes, such as the one shown by the Tracker module.

```
  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;

```

The value of the `NODE_NEW_LIMIT` is the number of seconds in 30 days.

To notice that when you visit the node, "new" is not anymore shown.
> 8 votes

---
Tags: views
---


# Question
Title: Can I add a link to the node reference when using the autocomplete widget?
I love the autocomplete widget for the References module in Drupal 7, but I find it odd that it doesn't include either a link to the referenced node (view or edit)?

Is there some way in hook\_form\_alter that I can add this somehow?

---

I can do this:

```
$form['field_lessons']['und'][0]['#suffix'] = '<a href="#">Edit</a>';

```

And the autocomplete field has an edit link underneath of it, but this doesn't work:

```
foreach($form['field_lessons']['und'] AS $lesson) {
  $lesson['#suffix'] = '<a href="#">Edit</a>';
}

```

And also loops 10+ times even though I only have 1 node reference currently :s

---

I don't necessarily like it but I can do it in Javascript like this and the Drag & Drop still works:

```
$('#edit-field-lessons .form-item').each(function(i) {
  var lesson_nid = $(this).find('input[type="text"]').val();
  lesson_nid = lesson_nid.substring(lesson_nid.indexOf('[nid:')+5, lesson_nid.indexOf(']'));

  $(this).append('<a class="view" href="node/' + lesson_nid + '">View</a>');
  $(this).append('<a class="edit" href="node/' + lesson_nid + '/edit">Edit</a>');
});

```

# Answer
This'll do the trick (I've tested it this time ;) ):

```
foreach($form['field_lessons'][LANGUAGE_NONE] as $key => $lesson) {
  // If we have a default value for the nid, we have a populated node reference
  if (isset($lesson['nid']) && is_array($lesson['nid']) && $lesson['nid']['#default_value'])) {
    // Get the nid
    $nid = $lesson['nid']['#default_value'];

    // Create an edit link
    $link = l('Edit', "node/$nid/edit");

    // Add it to the element
    $form['field_lessons'][LANGUAGE_NONE][$key]['nid']['#suffix'] = $link;
  }
}

```
> 1 votes

---
Tags: 7, nodes, ajax
---


# Question
Title: Adding attributes with hook_node_view_alter
I'm trying to modify the "Add new comment" link in certain nodes, and for this I'm using hook\_node\_view\_alter like this:

```
function example_node_view_alter(&$build) {
//    $build['links']['comment']['#links']['comment-add']['attributes']['class'] = 'nice small radius blue button';
      $build['links']['comment']['#links']['comment-add']['title'] = t('Add a review');
}

```

The commented line is causing trouble though,... since the array doesn't have a 'class' attribute. If I just add it to the array like that, every time I clic on the "add a review" link, the website isn't rendered properly... so how can I add it without ruining everyhting else?

# Answer
> 3 votes
The `class` property is an array so you need to initialise it like this:

```
$build['links']['comment']['#links']['comment-add']['attributes']['class'] = array(
  'nice',
  'small',
  'radius',
  'blue',
  'button'
);

```

---
Tags: hooks
---


# Question
Title: How to hide and/or prevent access to fields in a form,  such as group_audience for organic groups
This has been troubleing me for a while.. When i try to hide fields like the group audience field, or the publishing setting from a form, on validation the form set both of these field to a null value, even though the defaut value as been correctly declared.

I tried to use Invisible, #access, unset hidden nothing work! This is very troubleing because for my current project users can edit only small bits of their profile at the time, for instance just the address or the picture, so if i hide group audience the user ends up kicked out of the groups he belongs at every edit.

I ended up using the code below to hide these field while still keeping the user in their group.

```
$variables['user_edit_about']['group_audience']= $temp['group_audience'];
$variables['user_edit_about']['group_audience']['#prefix'] = '<div style="display:none;">';
$variables['user_edit_about']['group_audience']['#suffix'] = '</div>';

```

Would anyone think of a better way to achieve this ?

Thanks

# Answer
> 6 votes
Edit:

Ok I figured it out. Put this in your custom module:

```
function example_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'story_node_form') {
        $form['title']['#value'] = 'hot stuff';
        $form['title']['#access'] = FALSE;

    }
}

```

This will set the title of the story node to 'hot stuff' and it will NOT be render on the page because #access = FALSE;

You can add more granularity control inside hook\_form\_alter() like

```
  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['title']['#access'] = FALSE;
  }

```

This works for Drupal 6 & 7.

*Old Answer (ignore):*

Its been awhile since I did something like this, so I may have it wrong. If you set the `[#value]` of a form item, it will not be visible on the form.

I did this in Drupal 6, `hook_form_alter()` in a custom module. I don't know if it will work in Drupal 7 and I don't know if you can do it in a preprocess function

# Answer
> 5 votes
You can also just add the 'element-hidden' CSS class to the form element

```
$form['user_edit_about']['group_audience']['#attributes']['class'][] = 'element-hidden';

```

As iStryker mentioned previously, it would still be possible to change the value through DOM manipulation. However, this is a nice, easy way to hide a form field (or any other render element). The `element-hidden` class is defined in `system.base.css`.

---
Tags: forms, organic-groups, users
---


# Question
Title: How do I alter image field code without hacking core?
I need to change the style of the title in image field to be a text area rather than a text field. I can achieve this by hacking core in the following way:

# image.field.inc line 410

```
$element['title'] = array(
    '#type' => 'textarea',
    '#title' => t('Title'),
    '#default_value' => isset($item['title']) ? $item['title'] : '',
    '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
    '#maxlength' => variable_get('image_title_length', 500),
    '#weight' => -1,
    '#access' => (bool) $item['fid'] && $settings['title_field'],
  );

// Change '#type' => 'textarea'  to '#type' => 'textfield'

```

I don't though, want to hack core. How can I create a preprocess function to allow me to do this via my *template.php*.

# Answer
> 4 votes
You won't (easily) be able to use a preprocess function to do this as the element is generated by a form.

You could use a non-generic `hook_form_alter()` implementation to do this on a single form, but the best way would be to write a small custom module and implement`hook_field_widget_form_alter()` to override the element.

The alt and title fields (along with some others) are only added in a `#process` function of each image element (`image_field_widget_process()`), so you'll need to add your own `#process` function to run after that one, and alter the field type in there.

The following code is tested and seems to work well (including playing nicely with the AJAX functionality on the image field):

```
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an image field type
  if ($context['field']['type'] == 'image') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the title field to a textarea
  $element['title']['#type'] = 'textarea';

  // Return the altered element
  return $element;
}

```

It produces results like this:

It might be worth bearing in mind that the maximum size of the title column is set in the database, so you won't be able to go any higher than 1024 characters.

---
Tags: theming
---


title: Omega 16 Columns

text:
# Question
Title: Omega 16 Columns
By default, Omega is loading the 12 column grid (alpha-default-normal-12.css). How do I have it load the 16 column grid (alpha-default-normal-16.css)?

# Answer
> 4 votes
Goto the settings page for your theme, eg "admin/appearance/settings/mytheme".

Make sure you have the 960gs selected, and choose your default width (narrow, normal, wide, or fluid).

Open the "Zone and region configuration tab". Bang down into a zone, then the configuration for the zone. Choose your column count (12, 16, or 24). You need to do this for each zone; each zone can have a different column count.

Save your configuration.

---
Tags: 7, theming
---


# Question
Title: Where should I add the unique identifier cookie code?
I want to add a unique identifier in a cookie when the user (anonymous or logged) visits the website. Where should I call this code. I tried calling the code in hook\_init but that doesn't work on cached pages. Any help would be greatly appreciated. Thanks.

# Answer
I think `hook_boot()` would be the best place for your code:

> This hook is run at the beginning of the page request. It is typically used to set up global parameters which are needed later in the request.
>
> **Only use this hook if your code must run even for cached page views**.This hook is called before modules or most include files are loaded into memory. It happens while Drupal is still in bootstrap mode.

(emphasis mine)
> 0 votes

---
Tags: 6, cookies
---


# Question
Title: The body field for the comment form isn't being rendered
Here's the code I'm using to render the comment form, inside node.tpl.php:

```
$comment = new stdClass;
$comment->nid = $node->nid;
echo render(drupal_get_form('comment_form'), $comment);

```

But the output HTML is: Note the lack of the body field.

To start debugging, I implemented `hook_form_alter()` and used `print_r()` on the first `$form` argument that gets passed to the function. Here's the full output. It also seems to lack any indication of a body field:

```
Array
(
    [#node] =>
    [#id] => comment-form
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => comment-form
                )

        )

    [#theme] => Array
        (
            [0] => comment_form__node_
            [1] => comment_form
        )

    [#action] => /commons/comment/reply/
    [author] => Array
        (
            [#weight] => -2
            [_author] => Array
                (
                    [#type] => item
                    [#title] => Your name
                    [#markup] => Eric Biewener
                )

            [name] => Array
                (
                    [#type] => value
                    [#value] => Eric Biewener
                )

            [mail] => Array
                (
                    [#type] => textfield
                    [#title] => E-mail
                    [#default_value] =>
                    [#required] =>
                    [#maxlength] => 64
                    [#size] => 30
                    [#description] => The content of this field is kept private and will not be shown publicly.
                    [#access] =>
                )

            [homepage] => Array
                (
                    [#type] => textfield
                    [#title] => Homepage
                    [#default_value] =>
                    [#maxlength] => 255
                    [#size] => 30
                    [#access] =>
                )

            [date] => Array
                (
                    [#type] => textfield
                    [#title] => Authored on
                    [#default_value] =>
                    [#maxlength] => 25
                    [#size] => 20
                    [#access] =>
                )

            [status] => Array
                (
                    [#type] => radios
                    [#title] => Status
                    [#default_value] => 1
                    [#options] => Array
                        (
                            [1] => Published
                            [0] => Not published
                        )

                    [#access] =>
                )

        )

    [subject] => Array
        (
            [#type] => textfield
            [#title] => Subject
            [#maxlength] => 64
            [#default_value] =>
            [#access] => 1
            [#weight] => -1
        )

    [is_anonymous] => Array
        (
            [#type] => value
            [#value] =>
        )

    [cid] => Array
        (
            [#type] => value
            [#value] =>
        )

    [pid] => Array
        (
            [#type] => value
            [#value] =>
        )

    [nid] => Array
        (
            [#type] => value
            [#value] =>
        )

    [language] => Array
        (
            [#type] => value
            [#value] => und
        )

    [uid] => Array
        (
            [#type] => value
            [#value] => 0
        )

    [node_type] => Array
        (
            [#type] => value
            [#value] => comment_node_
        )

    [actions] => Array
        (
            [#type] => actions
            [submit] => Array
                (
                    [#type] => submit
                    [#value] => Save
                    [#access] => 1
                    [#weight] => 19
                )

            [preview] => Array
                (
                    [#type] => submit
                    [#value] => Preview
                    [#access] => 1
                    [#weight] => 20
                    [#submit] => Array
                        (
                            [0] => comment_form_build_preview
                        )

                )

        )

    [#parents] => Array
        (
        )

    [#pre_render] => Array
        (
            [0] => _field_extra_fields_pre_render
        )

    [#entity_type] => comment
    [#bundle] => comment_node_
    [#form_id] => comment_form
    [#type] => form
    [#build_id] => form--BpKXguXKLfbkSvL3gtwLoDDtogZ1qdrJDSm-JeiALw
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form--BpKXguXKLfbkSvL3gtwLoDDtogZ1qdrJDSm-JeiALw
            [#id] => form--BpKXguXKLfbkSvL3gtwLoDDtogZ1qdrJDSm-JeiALw
            [#name] => form_build_id
        )

    [#token] => comment_form
    [form_token] => Array
        (
            [#id] => edit-comment-form-form-token
            [#type] => token
            [#default_value] => 7sCRtZn-FudO7YYGoEA0unxc1Mr6d30_yXnfaU-6oJM
        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => comment_form
            [#id] => edit-comment-form
        )

    [#method] => post
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#tree] =>
    [#validate] => Array
        (
            [0] => comment_form_validate
        )

    [#submit] => Array
        (
            [0] => comment_form_submit
        )

)

```

I'm not sure what debugging steps to take next. Seems like maybe some other implementation of `hook_form_alter()` is removing that field, but I don't know how to look for that.

# Answer
You're passing the `$comment` variable as an argument to `render()` instead of `drupal_get_form()`, so the body field won't be attached.

Your last line just needs to change to:

```
echo render(drupal_get_form('comment_form', $comment));

```
> 1 votes

---
Tags: 7, forms
---


title: Dynamic fields?

text:
# Question
Title: Dynamic fields?
I have a content where admins can add a new page. For now, I have the following fields.

1. Section 1 Title
2. Section 1 Body
3. Section 2 Title
4. Section 2 Body

I like to make it so that admins can add x number of sections dynamically. Is this even possible in Drupal?

# Answer
You could use the Field Collection module to do this pretty easily.

You can set up a field collection containing your 'Title' and 'Body' fields (and any other number of fields you choose to add in the future), set the cardinality to 'Unlimited', and your users can take advantage of the in-built 'Add another' feature that fields has.

I normally install the Field Collection Table module as well, it offers a more UX friendly widget if you've got more than a couple of fields in the collection. I'm not sure how well this would work if you need to use a textarea for the body though.
> 4 votes

---
Tags: 7, entities
---


title: Redirect anonymous user to login page

text:
# Question
Title: Redirect anonymous user to login page
I need to redirect an anonymous user when they hit the url 'node/add/project' to 'user/login' - otherwise, just leave them enter that url.

Not sure if I'm going about this the correct way (probably not as it doesn't appear to work!) - Can someone shed some light, or advice!

```
function local_menu() {
    $items['node/add/project'] = array(
        'page callback' => 'local_project_anonymous',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function local_project_anonymous(){
    global $user;
    if($user->uid == 0){
        drupal_goto('user/login');
    }
}

```

Cheers

# Answer
```
function MODULE_init(){
  global $user;
  if ($user->uid == 0  && $_GET['q'] == 'node/add/project' ) {
    drupal_goto('user/login');
  }
}

```
> 6 votes

# Answer
Maybe you can use the LoginToboggan module.

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
>
> * Allow users to login using either their username OR their e-mail address.
> * **Allow users to login immediately.**
> * **Provide a login form on Access Denied pages for non-logged-in (anonymous) users.**
> * The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
> * Customize the registration form with two e-mail fields to ensure accuracy.
> * Optionally redirect the user to a specific page when using the 'immediate login' feature.
> * Optionally redirect the user to a specific page upon validation of their e-mail address.
> * Optionally display a user message indicating a successful login.
> * Optionally combine both the login and registration form on one page.
> * Optionally have unvalidated users purged from the system at a pre-defined interval.
> * Integrates with the Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example).
> 2 votes

---
Tags: 7, redirection
---


# Question
Title: Quicktab problem on the argument of view and block
I used to make a view shows a page of a project in the url: `projects/[node:author]/[node:nid]`, this view works well.

Now I want to display this view in the quicktab, but the problem is I can't view the content of the view. I think it is because of the configuration of argument of quicktabs. In the quicktabs, I have selected this view and display it as page, but the problem is I am not sure how to config the arguments.

As you have seen the url of view, is `projects/[node:author]/[node:nid]`, in which there are 2 arguments, when I set it as %0/%1, not working, %0/%1/%2, still not working, and set it as projects/%0/%1, not working either.

**Is there any problem with my config?**

Also in the quicktabs, I also display the comments related to that content, previously I made another block with default value as contextual argument like projects/\[node:author\]/\[node:nid\], but when I try to put it the quicktabs as a block, it also doesn't show.

# Answer
> 0 votes
Looks to be an issue with the quick tabs module. I have the same issue on version 7.x-3.4. It seems to break as soon as you use the % URL variables

**UPDATE**: After looking at the code, the module calls args(), in my case, the values returned from that are different than the URL. For example, my URL is "product/reading" however, quicktabs gets this Array ( \[0\] =\> node \[1\] =\> 180 ). So I have to change my view to use the node ID instead of the node title. This should have been noted in the modules documentation.

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


title: Creating Database

text:
# Question
Title: Creating Database
I want to create a student database in a Drupal website. There will be a page containing a form (name, id, age, phone)in the website, where data will be entered and stored. Later on the stored student list can be retrieved or perform some operations on the database like sending sms to all the students.

Please note that students are not the site users, some other user will enter all the details of the students.

I am a newbie to Drupal.. Please guide me on how to do that...

Thanks

# Answer
If you are requiring a front end to view the data stored I would highly recommend bui\[lding a bunch of custom views. You can then go further and install Views Bulk Operations to allow actions to be performed on multiple rows (students). You have send mail as a default option but for sending a sms you will need to install the sms framework

As for the containers, Drupal 7 has fields which can be attached to user profiles, if they get pretty advanced you can use the Profile2 module which just gives you a little more control.

If you dont need the attachment to an actual user account you can create a content type "student" which will allow you to add custom fields in the same way you can with a profile.
> 1 votes

# Answer
Make a content type for student. And using CCK add all the field i.e. name, age,etc.. For phone, CCK phone module will be helpful to you..
> 0 votes

# Answer
I think you should be using the default Drupal registration form, make the student entries users, even though you don't want them to sign in or anything like that. Put up some profile fields (I think this is the new Profile followup for D7, Profile 2) in which you could store some additional information and let them be filled on the registration form. Then afterward you could even export the users to CSV (Profile CSV). This way you could have some more flexible data to be used to for example SMS them.

Please make sure you configure a good default "Authenticated user" role, this role should not be assigned to any administrative functions. Or even better, create a new role "student" and be sure to assign the role to those new entries.

Using users is (I think) the right way to go, since you can afterwards (for unforeseen future proposes) even let the users login and share content which only students should be obliged to.
> 0 votes

---
Tags: views, 7, database
---


title: How to redirect a user to mobile site?

text:
# Question
Title: How to redirect a user to mobile site?
I have created a Drupal 7 site with all required functions. As per the requirement I have to create a mobile theme for this site, which I did effectively. Now problem is I need to redirect the user to the mobile site if the request is made from a mobile. If the request is made from computer he should be redirected to the main site.

Thanks in advance.

# Answer
> 1 votes
There are already existing modules to do it like mobile\_tools. Where u can set what theme to use for mobiles. and redirection on mobile detection also.

# Answer
> 1 votes
Mobile Tools is a good option, or you may use theme\_key just as well.

Regards.

---
Tags: theming
---


# Question
Title: How to implement search on multiple fields limited to one content type in drupal 7
I've created a new content type which has several fields (some of them are custom fields I created myself). Now I need to implement a search function on each of those fields.

This means that if I have these fields:

* VideoCV (video field)
* Occupation (text field)
* Driving licence (select lists)
* Region of birth (taxonomy term)

I need a search module with those four fields, so that if you search for occupation "engineer" it searches only data inserted in that specific field.

What do I need to do? What additional modules should I install? What should i do with my custom fields?

# Answer
If you need to access the nodes in code, delmi's solution should work.

If you want to use existing modules, views should do the trick. I found NodeOne's video tutorials on views very helpful: http://dev.nodeone.se/node/781
> 2 votes

# Answer
I'm not a D7 expert but I you can try with an EntityFieldQuery like this:

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                ->entityCondition('bundle', 'YOUR_CONTENT_TYPE_NAME')
                ->propertyCondition('status', 1)
                ->fieldCondition('YOUR_FIELD_NAME', 'value', $searchterm)
                // other conditions...
                ->propertyOrderBy('title')
                ->execute();
$nodes = entity_load('node', array_keys($entities['node']));

```
> 2 votes

# Answer
I wonder if Views and Better Exposed Filters would to the trick for you? Create a page view, expose your field filters, then in the "advanced" column to will have an option to show exposed filters in structure \> blocks.
> 1 votes

# Answer
Use the Finder module to build field-specific searches (Drupal's core search is a fulltext search, not field-specific). Here is an excerpt about it from the module's project page:

> ... allows Drupal site administrators to create flexible faceted search forms to find entities such as nodes or users based on the values of fields and database attributes.
>
> Typically Finder is used for these purposes:
>
> * As a search tool to find a group of nodes or users.
> * As a way to navigate to a specific node or user page that matches criteria.
> * As an alternative to exposed filters for a Views module display.
> 0 votes

# Answer
Create a view of your content type and add all the fields you want to search for as exposed filters. This creates a search form with input elements for all filtered fields (or just one if this is what you want). You can set it up to only filter for the filled input fields and ignore the other ones.

It let's you choose to put the search form on the top of your view or move it to a separate block.
> 0 votes

# Answer
**Solution 1**

Views 3 provides solution for your question from the box. It's the `Global: Combine fields` filter.

1. Add fields
2. Add `Global: Combine fields` filter to filter criteria
3. Check fields you want to combine in filter's settings

If you use Display suite or teasers mode - force using fields in the View setting.

**Solution 2**

Views filters populate \- good module. But there is 1 problem "only populates STRING exposed filters".

For more info, refer to the Views issue about Apply One Exposed Filter to Multiple Fields.
> 0 votes

---
Tags: 7, search, entities
---


# Question
Title: Remove content translation links from contact form
I'm having a difficult time diagnosing a problem on a site I'm working on. By default on a multilingual site Drupal puts "content translation links" at the bottom of nodes. I've disabled the content translation links in favor of the language switcher block. However, on the contact form from the contact module I still have what look like content translation links at the bottom of the form (see screenshot below).

In the screenshot the translation links that I don't want are labeled #1 and the language switcher block is labeled #2.

I've selected "hide content translation links" under /admin/settings/language/i18n , but I guess this doesn't apply to the contact form for some reason.

So far I've been able to deduce that these links are getting passed through the $content variable because when I remove `print $content` from page.tpl.php, the links (as well as the contact form itself, of course) disappear. It also seems that the links are being treated as part of the contact form itself; when I tried using the panels site contact page override, whenever I added the contact form widget the links were included.

I apologize if this is perhaps too "localized" (pardon the unintentional pun) a question, but any help with figuring out how to get rid of these content translation links from the contact form page would be greatly appreciated. On the one hand I highly doubt this is the expected default behavior, so I feel like I must have tripped a setting or missed a setting somewhere. But at the same time I've looked through pretty much everything I can think of, so I'm at a loss.

# Answer
> 1 votes
If this is a contact form problem only, you might be able to remove the links with `hook_form_alter` or alternatively css.

# Answer
> 2 votes
If you want to hide that button, you can use the CSS Injector module, create a CSS class to apply to that data, and set `display:none !important`. It's not necessary to use a Drupal hook.

# Answer
> 2 votes
If you use Drupal 7, you can put `hide($content['language']);` in node.tpl.php.

# Answer
> 1 votes
This is not only a Drupal 6 issue, I had the same problem on Drupal 7 until I solved it and found this discussion. My solution was to implement `template_preprocess_node()` in template.php and simply unset `$variables['content']['links']['translation']`.

Unlike Laxman i couldn't find any data in `$content['language']` in node.tpl.php and I don't think such variable exist. You can try this with `var_dump($content['language']);` and you'll get an empty result. However, `var_dump($content['links']['translation']);` will result in an array containing information on what languages current node has translations for.

A lot of help came from reading about translation\_node\_view in the Drupal API.

---
Tags: i18n-l10n
---


# Question
Title: After altering form I cannot save changes in nodes
In drupal 7: I have **Answer** content type and alter the form for that type:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'answer_node_form') {
    // disabling some fields (ie. #access title field to false)
    // setting defaults values
    // adding one hidden field (that shouldn't be inserted into database)
  }
}

```

A when I'm trying to submit edit form, the process of PHP takes too much time and Apache restarts. Do you have any idea what is wrong? Maybe when I send the form, it shouldn't have any additional fields?

I could paste the code but I think it's insignificant.

# Answer
As @NikhilMohan says, you can't just remove fields like the title; they're required for validation. Event setting `#access => FALSE` has strange results in my experience.

What you could do instead, is set a value for the fields you're hiding, and change their `#type` to `'value'`. That way the element will still exist on the server side, and validation/submission won't break.

e.g.

```
$form['title']['#type'] = 'value';
$form['title']['#value'] = 'Some default value for the title';

```
> 1 votes

---
Tags: 7, forms
---


title: ImageCache not working

text:
# Question
Title: ImageCache not working
I recently moved my website (Drupal 6) and database to a new server. I am now getting an error whenever I try to upload images using the image field. When I upload images the thumbnail doesn't appear and the error I get is:

"ImageMagick reported an error: libgomp: Thread creation failed: Resource temporarily unavailable"

I tried switching to using GD2 but this didn't make any difference. I've also checked that I have the correct temp folder set in the file system. I had migrated from a 1&1 hosting account to a newer 1&1 hosting account...

It seems like the ImageCache files are not being generated.

I'm not sure what to try next.

Any advice would be appreciated.

EDIT:

I also found that even inserting images that are already on the server into content are not showing up. The path is correct (I've checked the files) but they just don't appear.

Actually, hardly any images are showing at all throughout the website even though the paths are correct and when ImageCache is not even used.

# Answer
> 1 votes
I found a solution to my problem. There were two changes I needed to make.

The first was in the .htaccess file in the "files" folder there was the line:

```
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

```

When I commented out this line I could see the images again.

However, I was still having problems generating new ImageCache images. I managed to fix this by adding the line below to the settings.php file:

```
putenv("MAGICK_THREAD_LIMIT=1");

```

I find out this last solution from my hosts (1&1) technical support.

# Answer
> 0 votes
The two most common problem are: 1. You don't have write access to the folder on the server where image cache will generate the image cache preset image files. If you are on shared hosting, go to control panel and set the permission accordingly. And if you have SSH access run the CHMOD for permissions. 777 can work.

And check the file system if the temp folder is correct and accessible to write files because that folder is being used to generate images.

# Answer
> 0 votes
I came across the same situation. I just checked file permissions of the images folder(sites/default/files) in my server. U can right click on the files folder and then choose file permissions (make sure WRITE and EXECUTE checkbox's are checked for group and public permissions).

And the problem for improper functioning of images may be a module issue. so try to re-install the image module. It may work. hope this is may help you

---
Tags: 6, media
---


title: How do I change the search key length?

text:
# Question
Title: How do I change the search key length?
I'm using Search API and Fuzzysearch in D7, and it's unable to search for three letter words. Unfortunately, we have a TON of 3-letter acronyms at work, so these need to be searchable. I've looked in the Search API and Fuzzysearch settings, but can't see where to change the length of the search keys.

I get the following error message when searching:

> The following search keys are too short or too common and were therefore ignored: "api".

# Answer
go to `admin/config/search/settings` and change the length of Minimum word length to index to `2` and re-index the site.
> 2 votes

---
Tags: 7, search
---


title: Reusing code in .module and .inc files

text:
# Question
Title: Reusing code in .module and .inc files
I plan to develop a module (say M2) that uses a pre-existing module(M1) as a soft dependency. In short there are a number of functions that I can reuse from M1 in my module M2...

other than specifying M1 as a dependency in M2's .info file what other steps do I need to take to re-use M1's functions.. also since these aren't classes but functions so how can I inherit them ?

using module\_load\_include() function only includes the .inc file... but then what about the .module file of M1 ?

# Answer
If M1 is enabled, the .module file will be included on every page load anyway. And if M1 is a dependancy of M2, M1 will definitely be enabled if M2 is enabled.

It's only the other files (`.inc`, etc.) that might contain extra functionality that you'll need to load explicitly with `module_load_include()`.
> 2 votes

---
Tags: taxonomy-terms, 7, rdf
---


# Question
Title: How to edit files without changing the last modified date?
One of my sites recently got hacked with the dreaded pharma-hack. The hacker inserted `base64_decode`'d code into `includes/bootstrap.inc`

Initially I thought the FTP password was discovered since the password was quite weak.

However, the Hosting providers indicate that there has been no FTP access from other than my I.P. address. And also the file bootstrap.inc's "Last Modified" date has not been changed.

I let the client know to change his FTP password, and he's only done it a day after. However during that time, they changed another file `includes/cache.inc` (must've realised the code has been removed from `bootstrap.inc`), but the cache.inc's Last Modified date didn't change either. So now he's (client) changed his FTP password, but I'm worried that this hacker is gaining access not by through FTP, but by some other means.

I've thoroughly went through the site, and haven't noticed any abnormal, or out of place \*.php files uploaded into the directories. Maybe I haven't looked hard enough? What other means are there to change a file's contents without using FTP? And how to change a file without changing the modified date?

Drupal 6.

Thanks.

---

Update: Most likely an FTP breach, as the affected site had a very weak FTP password (8 char only, all lowercase, only alphabets). This was probably done through brute force guessing the password, and then uploading a file that's sort of like a file manager. I seen this file cleverly (well not so I guess) disguised as `LICESNE.php` (hacker can't spell :) ) and ironically I managed to hack this file and gain access to the administration screen.

From this page you can create new files, modify existing files and run scripts on the server, delete files, manage databases etc. It was a 1 page hacker administration page!

The sites have not had a breach now as I've done the security updates and changed the passwords to secure ones.

Again thanks for all the answers and comments. Much appreciated.

# Answer
Consider this PHP code:

```
touch('/path/to/file', strtotime('-1 month'));

```

That will change a file's modified date to one month ago.

It's pretty easy to mess with the modified date of a file if you've got access to the server, which your hackers obviously have (at least to some degree).
> 4 votes

---
Tags: 6, security
---


# Question
Title: How do you properly render the body when pulling it from the database using db_select?
I have a db\_select() that returns the \*body\_value\* and \*body\_format\* from the table field\_data\_body...how to I properly render that in Drupal?

# Answer
I think the 'proper' way to do this is not to get the data directly from the database at all, but to use the built-in field API:

```
// Get an entity (node in this case).
$node = node_load(1);

// Get the view for the body field
$view = field_view_field('node', $node, 'body');

```

Doing it this way you won't have to bother negotiating languages or anything that, and the field will be outputted exactly as it is when it's attached to a node display.

If you do want to do it manually, though, you need to use the `check_markup()` function:

```
$text = check_markup($body_value, $body_format);

```

It might be worth taking note of the comments in that function, you need to be careful about accepting an arbitrary filter format without validating it:

> Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using filter\_access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.
> 5 votes

---
Tags: 7
---


# Question
Title: What are the advantages of using Apache Solr over the core search module?
The Apache Solr Search Integration module project page states:

> Solr search can be used as a replacement for core content search and boasts both extra features and better performance.

What exactly are these extra features? (Or if there are too many, in what kind of use cases would I want to use Apache Solr?)

My site is hosted on Pantheon and they provide Apache Solr at no additional charge. Would this be something I definitely want to set up? Only set up in certain cases?

# Answer
> 13 votes
This article gives a thorough and straight-forward answer to your question.

> ### Performance improvements with Apache Solr
>
> High traffic sites running search queries against the database can start to degrade the site’s overall performance if the database becomes the bottleneck. This is also true for lower traffic sites with lots of content. Complex search queries can be slow to run.
>
> Requirements for features such as faceted search (see below) are becoming increasingly common. This can be delivered in conjunction with Drupal core search using the Faceted Search module but the inherent scalability and performance implications are well documented by the module’s maintainers.
>
> ### Other useful Apache Solr features
>
> Apache Solr also supports indexing and searching multiple sites (imagine internal intranet site and external corporate site), indexing attachments (eg PDFs, Excel documents) and recommended content blocks driven by a node’s taxonomy. The module page and the Acquia Search overview both have a good overview of the Apache Solr features that Drupal supports.

---
Tags: search
---


title: Why do I get a "page not found" error?

text:
# Question
Title: Why do I get a "page not found" error?
I have a working page listing items in a block (created by the 'block\_view' hook) which when displayed link to another set of pages where I want to list content types associated with them. The items are not standard drupal types so there is no relation between these two sets except through my DB table.

So say I have a link on the original page to **mysite/speech/3**, and I want to see all speeches associated with speech 3.
To do this I created a block, made it display on speech/\* and all is good. I can see the content types associated with speech 3 in a nice table, except it also displays a 'Page not found error' along with the correct data.

1. Why?
2. I'm trying to use the Drupal structure as far as possible where I can. When I can't are there issues with using blocks extensively performance wise?

# Answer
> 2 votes
1. You don't have a piece of content at that URL mysite/speech/3, only a block. Don't use a block in this situation, just use a regular page.
2. Blocks are fine if you can cache them. Does the data change often? If not, set a very long cache and there should very little performance impact.

---
Tags: blocks
---