# Question
Title: How to override the default zen html template depending on a node type?
I have a themes which inherit from **zen template**. The zen template has an `html.tpl.php`, and I would like to override that `html.tpl.php` for one **content type**.

Let's say my theme name is `test` and my content type is called foo, I have tried the following code snippet into my `template.php` located in my test theme

```
function test_preprocess_html(&$vars){
  if (!empty($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'html__node_' . $vars['node']->type;
  }
}

```

Then I have created my html template named `html--node-foo.tpl.php` in the `templates` folder.

And, it **doesn't works**! I keep having the default zen html template loaded.

Here is the source of the `html.tpl.php` file in the zen `templates` folder

Ps: the following snippet works for **overriding the pages templates depending on node type**. Why does the above snippet doesn't works?

```
function test_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__node_' . $variables['node']->type;
  }
}

```

# Answer
> 1 votes
Jonathan, your missing an underscore...

```
function test_preprocess_html(&$vars){
  if (!empty($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'html__node__' . $vars['node']->type;
  }
}

```

Your get it if you see whats suggested already be doing a var\_dump($vars).

This has nothing to do with the Zen theme, it's just core functionality.

To understand how this is formed you can take a look at the theme\_get\_suggestions() function in theme.inc

```
/**
 * Generate an array of suggestions from path arguments.
 *
 * This is typically called for adding to the 'theme_hook_suggestions' or
 * 'classes_array' variables from within preprocess functions, when wanting to
 * base the additional suggestions on the path of the current page.
 *
 * @param $args
 *   An array of path arguments, such as from function arg().
 * @param $base
 *   A string identifying the base 'thing' from which more specific suggestions
 *   are derived. For example, 'page' or 'html'.
 * @param $delimiter
 *   The string used to delimit increasingly specific information. The default
 *   of '__' is appropriate for theme hook suggestions. '-' is appropriate for
 *   extra classes.
 *
 * @return
 *   An array of suggestions, suitable for adding to
 *   $variables['theme_hook_suggestions'] within a preprocess function or to
 *   $variables['classes_array'] if the suggestions represent extra CSS classes.
 */
function theme_get_suggestions($args, $base, $delimiter = '__') {

  // Build a list of suggested theme hooks or body classes in order of
  // specificity. One suggestion is made for every element of the current path,
  // though numeric elements are not carried to subsequent suggestions. For
  // example, for $base='page', http://www.example.com/node/1/edit would result
  // in the following suggestions and body classes:
  //
  // page__node              page-node
  // page__node__%           page-node-%
  // page__node__1           page-node-1
  // page__node__edit        page-node-edit

  $suggestions = array();
  $prefix = $base;
  foreach ($args as $arg) {
    // Remove slashes or null per SA-CORE-2009-003 and change - (hyphen) to _
    // (underscore).
    //
    // When we discover templates in @see drupal_find_theme_templates,
    // hyphens (-) are converted to underscores (_) before the theme hook
    // is registered. We do this because the hyphens used for delimiters
    // in hook suggestions cannot be used in the function names of the
    // associated preprocess functions. Any page templates designed to be used
    // on paths that contain a hyphen are also registered with these hyphens
    // converted to underscores so here we must convert any hyphens in path
    // arguments to underscores here before fetching theme hook suggestions
    // to ensure the templates are appropriately recognized.
    $arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);
    // The percent acts as a wildcard for numeric arguments since
    // asterisks are not valid filename characters on many filesystems.
    if (is_numeric($arg)) {
      $suggestions[] = $prefix . $delimiter . '%';
    }
    $suggestions[] = $prefix . $delimiter . $arg;
    if (!is_numeric($arg)) {
      $prefix .= $delimiter . $arg;
    }
  }
  if (drupal_is_front_page()) {
    // Front templates should be based on root only, not prefixed arguments.
    $suggestions[] = $base . $delimiter . 'front';
  }

  return $suggestions;
}

```

Have a look at the $delimter argument. The default is '\__' for theme\_hook\_suggestions().

# Answer
> 1 votes
Maybe you simply have a typo in the code?

You get $vars in the template declaration but you're checking for `!empty($variables['node'])` (Which will always be false) it should be `!empty($vars['node'])`

---
Tags: theming
---


# Question
Title: Same SKU but different product - Drupal Commerce
I am facing a problem with the Products in a website made with Drupal 7 and Drupal Commerce.

As per the requirement, two admin can create products in the website with Same SKU and same name. But the difference will be the Stock number and the color etc.

As an example, Product A has SKU: 0001

The 1st admin Creates Product A with Price $10 and stock 10. The 2nd admin Creates the Same product with Same SKU with Price $20 and stock 5.

Is it possible to do? Or it's better to create new SKU each time? Please suggest.

# Answer
> 5 votes
**Short Answer:** No, SKUs must be unique.

**Longer answer:**
SKU is acronym for Stock Keeping Unit. It is a specific produkt that you have have on stock, like a gray medium sized T-shirt with V-neck for men. Had it had a different size, color ... it would have been an entirely different product.

SKU's were create to be able to keep track of these different products, even if there only is a slight change. This also means that SKUs must be unique, since a SKU is the code for a specific product.

The above is general for e-commerce and originates from physical stores with stock keeping etc. Drupal Commerce conforms to these standards, and so it is impossible to create two products with the same SKU.

---
Tags: commerce
---


# Question
Title: Outputting recent comments in a different part of the node
I have created a custom node, and at the bottom of this node I would like to show the latest three comments made on that node. I have added the code below to my template.php, and then loop through the array to get the data in my node:

```
if ((arg(0) == 'node') && is_numeric(arg(1)))
{
    $result = db_query_range('SELECT c.cid, c.nid, c.subject, c.name
    FROM {comment} c WHERE c.nid = :cid ORDER BY c.cid DESC', 0, 3, array(':cid' => arg(1)));

    $i = 0;
    foreach ($result as $record) {
        $variables['NewComments']['NewSubject'][$i] = $record -> subject;
        $variables['NewComments']['NewName'][$i] = $record -> name;
        $i++;
    }
}

else {
    $variables['errorCheck'] = t('nope fail');
}

```

However, I am having trouble outputting this into the node.tpl. Is there an easy way to do this, or should I try something else to tackle this issue?

Thanks

# Answer
> 1 votes
You can do that using views.

Then you can either add this view as a block or you can use http://api.drupal.org/api/views/views.module/function/views\_embed\_view/7 in node.tpl.php

---
Tags: comments
---


# Question
Title: User Register page is different if there is a destination parameter in the url
I'm trying to find where to go in Drupal to find out how a user register form is displayed.

If the url is user/register, a person is routed to a standard registration form.

However, if the url is user/register?destination=voucher, then that person is routed to a user registration form that mimics our popup modal registration form, however, is not in a popup. This is not the regular registration form.

I want to find where this is set so that if a destination parameter is in the url, to go to the standard registration form.

# Answer
> 1 votes
The `drupal_get_form()` returns a form array for rendering. In your case `drupal_get_form('user_register_form')`. You can use `drupal_render()` with the result to render the html output.

If you need to override the form, use `hook_form_alter()` and change the `$form_state['redirect'][] = 'your/redirect/path'`. Also try removing the destination param with `unset($_GET['destination'])`.

Here are some references:

# Answer
> 0 votes
The way I'd do it is write a very small custom module. I'd assume you know the ID of your custom register form, so replace the value of `$id_of_custom_register_form` variable with the id of your custom register form on function `custom_module_register_page()`. Here's the code:

custom\_module.info:

```
name = "Custom Module"
description = "Custom Module alters user/register menu"
dependencies[] = user
core = "7.x"
package = "Other"

```

custom\_module.module:

```
/**
 * Implementation of HOOK_menu_alter()
 */
function custom_module_menu_alter(&$items) {
  // Change the function that returns the page content with
  // our custom function that checks the destination parameter
  // and return the appropriate form
  $items['user/register']['page callback'] = '_custom_module_register_page';

  // Empty the arguments array
  $items['user/register']['page arguments'] = array();
}

/**
 * Custom page callback for user/register path
 */
function _custom_module_register_page() {
  $id_of_custom_register_form = 'id_of_my_custom_register_form';

  // If destination is set return $id_of_my_custom_register_form form
  if(isset($_GET['destination'])) {
    $form_id = $id_of_my_custom_register_form;
  }
  // Otherwise return normal register form
  else {
    $form_id = 'user_register_form';
  }

  return drupal_get_form($form);
}

```

---
Tags: users, uri
---


title: problem with including external library

text:
# Question
Title: problem with including external library
Below I check for file existence and its exists.

```
$path = libraries_get_path('nusoap') . '/nusoap.php';
if(file_exists($path)) {
    print file_get_contents($path);
    die;
}

```

But when I try to include it I get `500 Internal server error`.

```
$path = libraries_get_path('nusoap') . '/nusoap.php';
if(file_exists($path)) {
    require_once $path;
}

```

Owner and Group of all files are www-data

**EDIT**

```
[Mon Dec 24 12:59:12 2012] [error] [client 2.146.17.144] PHP Fatal error:  Cannot redeclare class XMLSchema in /sites/all/modules/fedora_store/nusoap/nusoap.php on line 2049, referer: http://127.0.0.1/fedora/store/transaction/2/mellat

```

# Answer
When you get fatal web server/PHP error it is very useful to check the logs. Usually Apache logs are placed in `/var/log/apache2/error.log` but it may differ.

> Owner and Group of all files are www-data

I must warn you that *www-data* should not be an owner for most PHP files. *www-data* usually needs only read permissions. But it is not directly related to this question.
> 4 votes

---
Tags: 7, theming
---


title: Enable DropDown using Ajax Call

text:
# Question
Title: Enable DropDown using Ajax Call
As given in the code below, I tried enabling select list `$form['answer']['answer1']` through AJAX callback, textbox is getting populated with value, where as the dropdownlist is not getting enabled. Any help?

```
function mymodule_search_block_form($form, &$form_state) {
  $options = array();
  $options['key1'] = t('value1');
  $options['key2'] = t('value2');
  $options['key3'] = t('value3');
  $options['key4'] = t('value4');

  $form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $options,
    '#ajax' => array(
        'callback' => 'ajax_select_callback',
        'wrapper' => 'profile-wrapper',
        'event' => 'change',
    ),
  );

  $form['answer']['profile_name'] = array(
    '#prefix' => '<div id="profile-wrapper">',
    '#type' => 'textfield',
    '#title' => 'Profile Name1',
  );
  $form['answer']['profile_name2'] = array(
    '#type' => 'textfield',
    '#title' => 'Profile Name2',
  );
  $form['answer']['answer1'] = array(
    '#type' => 'select',
    '#disabled' => 1,
    '#title' => 'Profiles',
    '#options' => $options,
    '#suffix' => '</div></br>',
  );
  return $form;
}

function ajax_select_callback($form, $form_state) {
  $form['answer']['profile_name']['#value'] = 'Profile 1';
  $form['answer']['profile_name2']['#value'] = 'Profile 2';
  $form['answer']['answer1']['#disabled'] = 0;
  return $form['answer'];
}

```

# Answer
Interesting question. The way I see it there are actually two parts to this. This first is, of course, your actual question and that can be easily solved:

```
// Your code in ajax_select_callback().
unset($form['answer']['answer1']['#attributes']['disabled']);
$form['answer']['answer1']['#disabled'] = 0;
// More of your code in ajax_select_callback().

```

When you set the `#disabled` property of a form element to `TRUE`, what Drupal does is simply add the `disabled` attribute to the element and allows the renderer (i.e. `drupal_render()`) to do its job. In your AJAX callback, the `$form` array passed is that of the rendered form. This means that the your dropdown element already has the `disabled` attribute on it. Therefore, when it is rendered again, it still shows up disabled. So, to prevent this, we simply remove the attribute.

However, you'd notice that when you submit your form after this, the value of the disabled dropdown (in `$form_state['values']`) may not be the value you chose after "enabling" it. This is because your form is not being re-built on the server which means that Drupal still thinks your dropdown is disabled and will refuse to process your input, simply ignoring it and using the default. If you are able to reproduce this, comment on this answer and I'll update this post with a solution for that problem.
> 4 votes

---
Tags: forms
---


# Question
Title: Stop Advanced Forum cutting off the username?
Im using the Advanced Forum module. Many of my users have long usernames which are being cut off (in the author information when they post a comment). Is it possible to lengten the limit before the text is cut off?

I cant see any settings for the Forum or Advanced Forum modules. Below is a theme hook that creates the author information (dont know if this is the right track or not).

```
/**
 * Theme function to show simple author pane when not using Author Pane.
 */
function theme_advanced_forum_simple_author_pane(&$variables) {
  $context = $variables['context'];
  // Sending the context rather than the account makes it work for anon comments.
  $name = theme('username', array('account' => $context));

  $account = user_load($context->uid);
  $picture = theme('user_picture', array('account' => $account));

  return '<div class="author-pane">' . $name . $picture . '</div>';
}

```

# Answer
> 2 votes
It seems Drupal core truncates the username to 25 characters. I have not tried this but this seems to be the solution for Drupal 7 (code added below for reference).

```
function MYTHEME_preprocess_username(&$vars) {

  // Update the username so it's the full name of the user.
  $account = $vars['account'];

  // Revise the name trimming done in template_preprocess_username.
  $name = $vars['name_raw'] = format_username($account);

  // Trim the altered name as core does, but with a higher character limit.
  if (drupal_strlen($name) > 25) {
    $name = drupal_substr($name, 0, 20) . '...';
  }

  // Assign the altered name to $vars['name'].
  $vars['name'] = check_plain($name);

}

```

Add this code in your theme's template.php file, and change MYTHEME to the machine name of your theme, and change the number `25` to something that fits your theme.

# Answer
> 1 votes
The code that truncates the username is in template\_preprocess\_username(). If you want to get a longer username, you can implement the following code in your theme, or your module.

```
function mymodule_preprocess_username(&$variables) {
  if (drupal_strlen($variables['name_raw']) > MYMODULE_MAXIMUM_USERNAME_LENGTH) {
    $name = drupal_substr($variables['name_raw'], 0, MYMODULE_MAXIMUM_USERNAME_LENGTH - 5) . '...';
    $variables['name'] = check_plain($name);
  }
}

```

`template_preprocess_username()` is executed before `mymodule_preprocess_username()` (or `mytheme_preprocess_username()`), which is then executed before theme\_username().

As `template_preprocess_username()` sets `$variables['name_raw']` to the raw username, all your module/theme needs to do is to set `$variables['name']` truncating `$variables['name_raw']` to the length you want. (Replace `MYMODULE_MAXIMUM_USERNAME_LENGTH` with the desired length.)

```
  // This is the code executed from template_preprocess_username().

  // Set the name to a formatted name that is safe for printing and
  // that won't break tables by being too long. Keep an unshortened,
  // unsanitized version, in case other preprocess functions want to implement
  // their own shortening logic or add markup. If they do so, they must ensure
  // that $variables['name'] is safe for printing.
  $name = $variables['name_raw'] = format_username($account);
  if (drupal_strlen($name) > 20) {
    $name = drupal_substr($name, 0, 15) . '...';
  }
  $variables['name'] = check_plain($name);

```

If you don't want to truncate the username, you can use the following code, in a module, or a theme.

```
function mymodule_preprocess_username(&$variables) {
  $variables['name'] = check_plain($variables['name_raw']);
}

```

---
Tags: nodes
---


# Question
Title: How to redefine default theme_image() function?
By default drupal use theme\_image() for render images. How to set for render custum function, ex. theme\_cus\_image()?

# Answer
If your purpose is overriding `theme_image()`, and make Drupal (or third-party modules) use your theme function when calling `theme('image')`, then you need to implement hook\_theme\_registry\_alter().

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['image'])) {
    $theme_registry['image']['function'] = 'theme_cus_image';
  }
}

```

Implementing that code, when a module uses code similar to the following one, it will call your function, and not `theme_image()`.

```
$form['enable'] = array(
  '#markup' => theme('image', array('path' => 'misc/watchdog-error.png', 'alt' => $status_short, 'title' => $status_short)),
);

```

If you need to override `theme_image()`, and use your code when the image class is a specific one, and `theme_image()` in the other cases, then you should use code similar to the following one.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['image'])) {
    $theme_registry['image']['function'] = 'theme_cus_image';
  }
}

function theme_cus_image($variables) {
  if (!empty($variables['attributes']['class']) && $variables['attributes']['class'] == 'the class you are looking for') {
    // Add your code.
  }
  else {
    return theme_image($variables);
  }
}

```

The problem with that code is that it is assuming no other module overridden the same theme function. If another module with a lower weight (or for which its `hook_theme_registry_alter()` is executed first) overrides `theme_image()`, the new theme function would not be called from the code I shown, as it explicitly calls `theme_image()`. It is also not possible to call the original theme function with `theme('image')` as that would cause an infinite loop: `theme('image')` would call `theme_cus_image()`, which would call `theme('image')`, which would call `theme_cus_image()`, which would call `theme('image')`, which would call \[…\].

Keep in mind that, with Drupal 7, preprocess functions are invoked also for theme functions that don't use template files. If you want to replace `theme_image()` just to alter one of the variables it gets, then you can use code similar to the following one, which unsets the width, and the weight of the image.

```
function mymodule_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
    unset($variables['attributes'][$key];
  }
}

```

Similarly, if you would want to alter the class assigned to the image, you could use the following code.

```
function mymodule_preprocess_image(&$variables) {
  if (!empty($variables['attributes']['class']) && $variables['attributes']['class'] == 'the class you want to alter') {
    $variables['attributes']['class'] = 'your class';
  }
}

```

If your purpose is defining a new theme function that is used from your module, then you simply need to implement hook\_theme().

```
function mymodule_theme() {
  return array(
    'cus_image' => array(
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
    ),
  );
}

```

In this case, `theme_cus_image()` will be used from code that calls `theme('cus_image')`. The code that calls `theme('image')` will still be using theme\_image().
> 3 votes

---
Tags: theming, media
---


# Question
Title: Can I have multiple nested forms within the same fieldset?
I am building a custom module that adds a form to certain node types that allows the user to fill/save some additional information about the node.

I would like to have 2 buttons. 1 which saves the data entered (currently working) and another which posts the data to an external script.

I can get this working by creating two different forms and settings their #action's accordingly but I would like the form markup all in a single fieldset, is this possible?

# Answer
> 2 votes
You can have both buttons in the same form. Inside the form's #submit handler (or each button's separate #submit handler), based on which button has been used to submit the form, you can either save the data, or do a `drupal_http_request()` to execute the external script.

Your form would include buttons roughly like this:

```
'save' => array(
  '#type' => 'submit',
  '#value' => t('Save'),
  '#submit' => array('save_function_name'),
),
'process' => array(
  '#type' => 'submit,
  '#value' => t('Process'),
  '#submit' => array('process_function_name'),
)

```

Then, the two functions `save_function_name()` and `process_function_name()` would do the job.

# Answer
> 1 votes
You can acccomplish that by calling drupal\_render() and passing it the fieldset and its children.

The twitter module does this for the Drupal 6 version. See the following usage example:

```
$add_account = array(
  '#type' => 'fieldset',
  '#title' => t('Add Twitter accounts'),
  '#weight' => 5,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#children' => '',
);

if (user_access('add authenticated twitter accounts')) {
  $add_account['#children'] .= drupal_get_form('twitter_auth_account_form');
}
if (twitter_connect()) {
  $add_account['#children'] .= drupal_get_form('twitter_non_auth_account_form');
}
$output .= drupal_render($add_account);

```

---
Tags: forms
---


# Question
Title: How to output the Panel node's template name in the Body class list
Is there a way to access a Panel's template name to output in the body of the page?

# Answer
Here is what I'm using in my Zen subtheme's template.php

```
// Add the panel's template name to the page's body classes
if($panel_page = page_manager_get_current_page()) {
  $display = panels_get_current_page_display();
  $layout = $display->layout;
  $variables['classes_array'][] = 'panel-layout-' . $layout;
}

```

Hope that helps!
> 0 votes

---
Tags: panels, theming
---


# Question
Title: How can I prevent users from entering invalid e-mail addresses at registration?
Sometimes users mistakenly input the wrong e-mail address upon user registration. When this happens, they are unable to activate their account, because the password is e-mailed to their e-mail address (or, in my case, I'm actually using Logintoboggan, but they still need to click the link in their e-mail before their account can be activated).

Often in this situation, the user will realize their mistake and simply re-register. This is ok, but then I have to clean up the accounts that never get activated, which is a pain. I've noticed that the Drupal 7 registration will accept a bad domain in the e-mail address by default (for example, yahoo.co.jap, which is an invalid TLD). When I realized this, I thought surely someone has already written a module to cover this use case (making sure users input a valid e-mail address on registration), but I was unable to find it. Does such a module exist?

# Answer
Drupal validates the email since Drupal 5; since Drupal 7, valid\_email\_address() (the function used to validate the email entered during registration, or when editing a user account) calls filter\_var().
The code used to validate the email address doesn't check if the domain exists, the username doesn't contain typos, or the domain has an active email server. While it would be possible to check if the domain has an email server by looking at its MX records with checkdnsrr(), it would be more difficult to verify if the username is correct, as most of the SMTP hosts doesn't return a useful value for the VRFY command (which means they always return ERROR, or OK).

Notice that the documentation for getmxrr() contains the following note.

> This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to RFC 2821 when no mail exchangers are listed, `$hostname` itself should be used as the only mail exchanger with a priority of 0.

I would rather do as @Letharion suggested, and implement `hook_cron()` to get ride of those accounts created by users who didn't type their email correctly. For Drupal 7, I would use the following code.

```
function mymodule_cron_queue_info() {
  $queues['mymodule_delete_users'] = array(
    'worker callback' => 'user_delete_user',
    'time' => 30,
  );

  return $queues;
}

function mymodule_cron() {
  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', 'user')
    ->entityCondition('entity_id', 1, '>')
    ->propertyCondition('access', 0)
    ->propertyCondition('created', REQUEST_TIME - MYMODULE_DELAY, '<')
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

  $result = $query->execute();

  if (isset($result['user'])) {
    $queue = DrupalQueue::get('mymodule_delete_users');
    foreach (array_keys($result['user']) as $uid) {
      $queue->createItem($uid);
    }
  }
}

```

The module should define the constant `MYMODULE_DELAY`, and set it to an appropriate value.
> 3 votes

# Answer
This doesn't answer your question, but perhaps solves your problem.

Use a Rules rule or a hook\_cron implementation that removes accounts that have never been logged into, but created more than X days ago.
> 2 votes

# Answer
Consider using Inactive Users module, to send a warning first and then delete the inactive modules.
> 0 votes

---
Tags: users, emails
---


# Question
Title: Overriding the search block module output to add a custom wrapper
My problem is fairly simple. I have written a theme\_form() to override the default but I want it to kick in only in the search block. How can I do this with Drupal 7? Thanks

# Answer
Put search-block-form.tpl.php into your theme directory, and modify it as you wish.

Another way is using `hook_form_FORM_ID_alter()`.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function HOOK_form_search_block_form_alter(&$form, &$form_state) {
  $form['#prefix'] = '<div class="custom-wrapper">';
  $form['#suffix'] = '</div>';
}

```
> 2 votes

---
Tags: theming, hooks
---


# Question
Title: How to use curly braces in schema default value?
I have a long varchar field that I'm using to save serialised data with `drupal_write_record`. I'd like to set the default value of the column to "a:0:{}" (which is `serialize(array())`).

However, when Drupal runs database updates, they are run through the `update_sql()` function which includes the default value in the query. This means that the '{' and '}' are interpreted as prefixing table names and removed, leaving the actual value of "a:0:" in the database, which is not what I want.

Is there a way to use curly braces in a field spec's "default" value?

# Answer
In your schema, for the field you want to serialize, you can add the key `serialize => TRUE` and use the `drupal_write_record()` function to write the field in the database. After, you have just to send a simple `array()`(without `serialize()`) and Drupal will do it by himself.

You can have more information in the documentation.
> 0 votes

# Answer
If you use db\_query, you can do something like this, normally only the curly braces inside the SQL string are replaced.

```
db_query("UPDATE {mytable} SET myfield = :data", array(':data' => "a:0:{}"));

```
> 0 votes

# Answer
There is already a bug report for Drupal 6, Impossible to insert serialized data with update\_sql(), but the bug was never fixed.

The issue is only for Drupal 6, as Drupal 7 doesn't use anymore `update_sql()`. The only workaround is using your own function, instead of `update_sql()`.

```
function mymodule_update_sql($sql) {
  $args = func_get_args();
  array_shift($args);

  $result = db_query($sql, $args);
  $sql = mymodule_query_get_string($sql, $args);
  return array('success' => $result !== FALSE, 'query' => check_plain($sql));
}

function mymodule_query_get_string($query) {
  $args = func_get_args();
  array_shift($args);
  $query = db_prefix_tables($query);

  if (isset($args[0]) and is_array($args[0])) {
    // All arguments are in one array.
    $args = $args[0];
  }
  _db_query_callback($args, TRUE);
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  return $query;
}

```

You can use `mymodule_update_sql()` in the same way you use `db_query()`, as it can use placeholders.
> 0 votes

---
Tags: 6, database
---


# Question
Title: How do I increase the memory assigned to PHP?
I have a script that saving the hundreds or thousands of nodes at one time and It is nearly impossible to manage it with `Batch API`. When I am running my script it saying :

> **Fatal error**: Allowed memory size of 268435456 bytes exhausted (tried to allocate 16 bytes) in /home/staging-uls/www/sites/all/modules/token/token.module on line 461.

I set the memory using `ini_set('memory_limit','256M')`. My script is still so long that showing the error. Is there any other way to do so?

What my script is doing exactly:

1. It fetches a data from other site using cUrl. The data are articles, journals and some other user's data.
2. After getting the data in XML format, it adds each content.

# Answer
I increased the max\_execution\_time to unlimited and I used `output buffering` for keep my script in progress. Change the memory limit to `1024M`. I got it from This URL.
> 0 votes

---
Tags: 6
---


# Question
Title: Cron run exceeded the time limit and was aborted + How to change max_exec_time if not access on php.ini
I am running a script which Fetches the data from other site like `Articles` of a user and other things also. I run my script in `hook_cron`. Cron gives me this error after a while of script running.

`Cron run exceeded the time limit and was aborted`.

Also I don't have access to change php.ini and setting.php. How can I change `max_exec_time` value.

# Answer
> 0 votes
Contacted to my client and get Access to files.

# Answer
> 1 votes
Seeing as you don't have access to anything that allows you to change the max execution time (and I would imagine if you find a workaround that it won't work if your server is this locked down) I see a couple of options.

1: Utilise the Batch API as I mentioned in my comment (Batch API docs are here)

2: Check out Elysia Cron to split your cron tasks up into smaller, more manageable chunks.

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

# Answer
> 0 votes
.htaccess is another option for increasing max\_execution\_time, if you have access to that. See https://stackoverflow.com/questions/7739870/increase-max-execution-time-for-php.

---
Tags: 6, cron
---


title: Re-attach behavior?

text:
# Question
Title: Re-attach behavior?
I'm trying to change a global setting for Drupal's js. I have this on my callback:

```
$setting['stopWatch']['startTime'] = 4000;
ajax_command_settings($setting, TRUE),

```

I was wondering how I would reattach this behavior after the ajax call is finished. I have this for my js:

```
Drupal.behaviors.stopWatch = {
  attach: function (context, settings) {
    $('#stopwatch').stopwatch({startTime: settings.stopWatch.startTime}).stopwatch('start');
  }
};

```

Also, I'm not sure why `startTime` isn't available in settings on `Drupal.behaviors.stopWatch` when I do `ajax_command_settings($setting);` instead.

# Answer
This will not add variables to settings. Function `ajax_command_settings()` just creates ajax command, that could be added to commands array. If you want to update settings after view ajax completed you should use something like this:

```
/**
 * Implements hook_views_ajax_data_alter().
 */
function module_name_tricks_views_ajax_data_alter(&$commands, $view) {
  if ($view->name == 'your_view_name') {
    $setting = module_name_get_settings($view);
    $commands[] = ajax_command_settings($setting, TRUE);
  }
}

```
> 1 votes

---
Tags: 7, ajax
---


# Question
Title: What is the correct thing to do when reusing code from an old, abandoned project?
I've recently reused the source code from an old project - Anonymous Publishing that seems to have been abandoned around 2008 as a Drupal 5 development version. There has never been an official release of Anonymous Publishing

I'm interested in the functionality Anonymous Publishing offers for my some of my own Drupal 7 sites, and have started work to convert it to Drupal 7. The conversion project is currently in my sandbox. However, the entire idea for this module and about 80 % of the code in the sandbox is from the original author (Ronny López).

I plan to develop this to the point when it is fully debugged and tested, and ready to be placed under drupal.org/projects as an "official" contributed module.

I wonder: What is the "right" thing to (do according to protocol on Drupal.org)? I believe my options are:

1. To request to become the official maintainer of the abandoned module, and to release my Drupal 7 port as a "continuation" of the abandoned module.
2. To release my project as a "new" module, with just an acknowledgement pointing back to the previous project.

My question is: What is generally considered the correct thing to do in a case like this?

# Answer
Request to become the new maintainer, and push your changes as the continuation of the old project.

That is the correct thing to do.
> 5 votes

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


title: D7 update field in database problem

text:
# Question
Title: D7 update field in database problem
```
function sms_user_delete($uid, $number = FALSE) {
  userfieldmobil_user_update($account->uid); // my custom field about users i call this manually.
  $query = db_delete('sms_user')
    ->condition('uid', $uid);
  if ($number) {
    $query->condition('number', $number);
  }
  $num_deleted = $query->execute();
}

function userfieldmobil_user_update($uid) { // i make it manually not able to update this
$num_updated = db_update('field_data_field_mobilnumber')
->fields(array(
'field_mobilnumber_value' => '',
))
->condition('entity_id', $uid, '>=')
->execute();
}

```

What i'm doing wrong sms\_user delete OK but my custom field has value but not updated.

# Answer
> 2 votes
If you want to update your field when user was deleted you should put your `update` query into your `sms_user_delete`. Because `userfieldmobil_user_update` will only works if u update user data, not delete it.

```
function sms_user_delete($uid, $number = FALSE) {
  userfieldmobil_user_update($account->uid); // my custom field about users i call this manually.
  $query = db_delete('sms_user')
    ->condition('uid', $uid);
  if ($number) {
    $query->condition('number', $number);
  }
  $num_deleted = $query->execute();

  $num_updated = db_update('field_data_field_mobilnumber')
     ->fields(array(
     'field_mobilnumber_value' => '',
     ))
     ->condition('entity_id', $uid, '>=')
     ->execute();
  }

```

Its not like in `drupal 6` where u can use `hook_user`, read about hook\_user\_update and hook\_user\_delete for more info.

---
Tags: 7, entities
---


# Question
Title: How to get the value of a variable in CCK from Devel?
I am using a custom .tpl file to theme teasers, and I am having trouble with the value of a variable returning `true` even when apparently there is no value inside (`$picture`). I would like to see what exactly this variable contains.

How do I leverage Devel to view this variable without having to `var_dump()`? Currently, the teasers are inside a view which is inside a block on the home page.

# Answer
> 1 votes
As you mentioned after enabling the Dev module, you can use `dpm($variable);` to get a detailed graphical listing of the array values.

---
Tags: 6, debugging
---


# Question
Title: conditionally hide a field based on another field's value (without using templates)
I have a content type which has a required field containing some personal information like an email address. This field is *not* on the user entity - it is on an arbitrary content type.

What I need to do is conditionally hide or show this value based on whether the user consents for this information to be shown publicly.

I know that this can be done by creating a second boolean field ("show information" or similar) on the content type, and then overriding the theme template. The problem is that I am using a number of different view modes (via displaysuite) and do not want to have to override them all individually. I've tried calling hide() in hook\_node\_view with no success. I also can't just hide the value with jquery/css, since this field contains personal information and I *can't* output it at all if the user doesn't consent.

Is there a way to do this using display suite or a custom module? Is there a common solution to this that I'm overlooking?

# Answer
> 1 votes
Implement hook\_field\_access($op, $field, $entity\_type, $entity, $account).

To find out how the arguments are structured, `var_export()` them in your first implementation (or better yet, `dpm()` them).

# Answer
> 1 votes
Try User Field Privacy module. It exactly does, what you are looking out for.

---
Tags: entities
---


# Question
Title: Programatically add module block to dashboard
Is there a way in which from my .module file I can assign a block in a specific region from Dashboard?

# Answer
It can be done in a simple way by mentioning a region key to the $blocks array in the HOOK\_block\_info(). Follow the code for reference,

```
    /**
     * Implements hook_block_info()
     * @return array
     */
    function my_module_block_info() {
      $blocks = array();
      $blocks['leaderboard'] = array(
        'info' => t('Leaderboard'),
        'status' => 1,
        'region' => 'dashboard_main',
        'weight' => 99,
        'cache' => DRUPAL_CACHE_PER_ROLE,
      );

      return $blocks;
    }

```
> 1 votes

# Answer
In .install file you can add following sql (change the appropriate values)

```
db_query("INSERT INTO {blocks} VALUES ('gjg', '0', 1, 0, 1, 0, 0, 1, 'my*', '')");

```
> 0 votes

# Answer
yes. see hook\_block\_info for **region**
> 0 votes

---
Tags: 7, blocks
---


title: Nodes with Views

text:
# Question
Title: Nodes with Views
I am trying to construct a page template where I display node information in the content area, and some views in a sidebar that display data from another node type. I am using the Entity Reference module. I am displaying apartment units, and these unit content types have a many-to-one relationship to its community complex. So, when the user views the unit profile, its community data will pop up on the side.

Anyone know the best way to go about doing this?

# Answer
> 1 votes
Have a `node_reference field` in the content type `Apartment Unit`.

Use `node id from content` as the contextual filter.

Use the `node_reference field` as a relationship in the view that you create. When you go to the fields section now(after adding the relationship), now you can add the fields from the referenced community complex.

# Answer
> 0 votes
I figured it out. In the view, in Relationships, choose Entity Reference: Referencing Entity. Click 'Require this relationship'. Next, add a Contextual filter for Content:Nid. Under Relationship, select the ID you set up in Relationships.

For 'When the filter is NOT available', select 'Provide default' with 'Content ID from URL'. Below that, for when filter IS available, select Validator.

That worked for me.

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


title: How do I use URL aliases in menus?

text:
# Question
Title: How do I use URL aliases in menus?
I am kicking the tires on Drupal 7 by spinning up a test site.

I chose the Danland theme and created various pages with URL Aliases for each, but when I create the Menu link for each, I can only enter the node in the "Path" field for the menu link and not the alias. So I can only enter "node/20" and not "about-us" (the alias for the node) in the menu.

I'd like the menu items to resolve to the aliases and not the nodes.
How do I do that?

# Answer
It appears that updating my Drupal install from Drupal 7 to the newly released Drupal 7.2 fixed the problem. It was either that or the updated SQL Server drivers that were just released which you'll need to install over the original PDO SQL Server drivers for the update scripts to work if you're updating to Drupal 7.2.

Either way, now the aliased URL shows up when I click on a menu link. So it could be either the code changes in Drupal core 7.2 OR the SQL Server driver updates. I am not 100% sure which one it is.
> 0 votes

# Answer
As Berdir mentioned in the comments and Greg in his answer, the following methods of adding path aliases should *Just Work*™.

* Adding it on the node submission form during node creation/editing
* Using the Pathauto module to automatically create path aliases
* Manually adding path aliases on *Configuration → Search and metadata → URL aliases*

Try clearing the cache from *Configuration → Development → Performance*. This should rebuild Drupal's menus and correctly show the path aliases.
> 7 votes

# Answer
I could also be that you are browsing the site in a different language than the url alias was created for. If you create an alias while browsing in German (say), visitors browsing the site in English mode will still see node/234234 . Just a tip.
> 4 votes

# Answer
If you assign both the path alias and the menu entry **using the node add/edit form**, then the created menu items will use the aliased paths. For simple use cases you shouldn't need to manually create aliases on the `admin/config/search/path` page or manually create menu entries on the `admin/structure/menu` page.
> 0 votes

# Answer
I just tried with a new d7 installation using the Danland theme and it works properly. If you can't get it working you can always specify an external url in your menu right? Such as 'http://yourdomain.com/about-us' intead of 'node/1'
> 0 votes

# Answer
Theme templates can be overridden with URL alias in the following way.

1. Add a preprocess function in theme template file
2. Get the URL alias, and choose the template file

The full explanation with code is given in How to create a template for page created in drupal Admin with URL alias.
> 0 votes

---
Tags: 7, routes, path-aliases
---


title: How can I insert PHP code in Views?

text:
# Question
Title: How can I insert PHP code in Views?
I tried the `views_php` but I have no luck. Any link to its documentation?

I want to add some custom field with PHP code inside it but the one I did return nothing. Please see the attached picture.

# Answer
Yes you can add php code using views\_php

Add field in views global Then add code you need is in Output code sector. I thing here is the problem for you. you add php code to 'Value code'. Then look at the preview. it's done!!!!!!
> 10 votes

---
Tags: 7, views
---


# Question
Title: How to access cookies in Views PHP Code filter?
I have a view that will display nearby locations.

The center coordinates would come from a cookie (lat,lng).

I am trying to get the cookie with $\_COOKIE, but I get an error saying that it is not set.

How would i access that cookie and return in for a proximity filter i Views (Using the Location module)?

# Answer
Checked with the views php module.

Then i get the cookies stored.
> 1 votes

# Answer
Try to check with the $\_SESSION variable, e.g.

```
$value = $_SESSION['something'];

```
> 0 votes

---
Tags: views, location, cookies
---


# Question
Title: How to get/access field values while inside hook_block_view?
I want to access the values of my field inside `hook_block_view()`.

I tried with field\_get\_items(), and field\_view\_field() with no luck.

By the way the block is showing in a page. Is there a way to get the values set in the content type field settings?

# Answer
> 1 votes
You seem to need information about the field itself and not about its instances (neither globally nor in the context of a given entity).

Hence, you would want to do a:

```
$field = field_info_field('field_my_field');
$keys = array_keys($field['settings']['allowed_values']);
// $keys will now have the set of unique keys for your options as set from
// the field settings page. Eg. Alsace, Aquitaine etc.

```

`field_my_field` is the unique name of your field that you have also attached to a content type. To find this out, ensure the *Field UI* module is enabled, go to the *Manage fields* page for your content type and look up the *Name* column for the field in question.

If you are interested in knowing how the values you had set from the settings form go here, check out `list_field_settings_form()`. Here is a link to the documentation of `field_info_field()` as well.

---
Tags: 7, entities, blocks
---


# Question
Title: Users field manually delete from database cache problem
i manually remove a column of field\_data\_field\_about in database belongs to some users. and this field is user field. And after in admin panel i edit this user which i delete this user column from database. But this user about value is shown there. Then i Clear All Caches then i come back to edit this user the about value is gone.

How can i disable cache for users fields?

# Answer
> 0 votes
I'm really not sure why you'd want to remove a column from a field table but just looking at your problem as is, a way by which you can disable caching of field values in the `cache_field` bin is by letting Drupal know that you don't want values for the field instances attached to a given entity type to be cached at all.

You can do this by implementing `hook_entity_info_alter()` from a custom module and setting the `field cache` key for the `user` entity as shown below:

```
function mymod_entity_info_alter(&$info) {
  $info['user']['field cache'] = FALSE;
}

```

You might find the documentation of `hook_entity_info` here useful. You might also want to lookup the definition of `field_attach_load()` from here.

---
Tags: users, database, caching
---


title: Store an array in drupal 7 field

text:
# Question
Title: Store an array in drupal 7 field
I have an use-case where a large associative array is getting generated while saving a node. The array is for a specific content type. I want to save the array along with the node.

While saving all the values of an array to different fields is not practical; Should I parse the array and save it as a string to a certain field so that I can get the array back while fetching?

If so, which one would be better : serialize or json\_encode.

While I heard serialize is not reliable all the time, json\_encode's purpose is not the same what I am going to use.

Briefly, **I want to store a dynamic associative array against a node.**

Any suggestion?

# Answer
`serialize` is better for small array, cuz `unserialize` will work faster. So if you work with huge data use `json_encode` &`json_decode`. Comparison PHP Serialization vs JSON Encoding for an array and your question already answered here on `stackoverflow` you can find more information about your question.
> 5 votes

---
Tags: 7, entities
---


title: Difference between .inc and .module?

text:
# Question
Title: Difference between .inc and .module?
I am trying to figure out what the main difference is between `mymodule.module` and `mymodule.admin.inc`.

Can anybody explain it?

# Answer
Without going into the ins and outs, Drupal understands the .module file as being a module within the system. The .inc notation has always been used in PHP for 'include' files. When developing modules you might want to split functionality into different .inc files.

Modules being used in specific cases use conventions similar to .admin.inc. That file typically includes all the code necessary to run the administrative interface, and a file node.pages.inc for example contains the code executed for other menu callbacks.
> 20 votes

# Answer
Adding on to the answer given by Alex Gill

1. .module files are loaded on every load page, whereas .inc files are loaded only when they are requested.
2. By convention .module files should contains only those functions which are implementation of hooks. Following this standard improves the performance too.
3. .inc files can be included by mentioning the path in `hook_menu()`, or by making an explicit using module\_load\_include('inc', 'node', 'node.admin').
4. If any of the .inc files contains class objects, it should be mentioned in the .info file of the module.
> 17 votes

# Answer
In short, mymodule.module is the php file that drupal automagically loads when that module is enabled. It can then include other files when needed. Usually, mymodule.admin.inc is included to create its admin settings menu. If you grep through mymodule.module, you can see where. Sometimes when a module gets pretty complex, it is broken up into smaller files and they are then included as well.
> 9 votes

# Answer
Difference between module file and inc file

* .module file can be loaded by drupal for every page load. function in the module file can be used in other module file with out including that module(\* but need to enable and dependency need to be added).
* .inc file can be loaded by manually. It need to contains specific page functions.

For example hook\_node\_load, hook\_form\_alter need to be in .module file.
> 1 votes

---
Tags: 7
---


# Question
Title: Why the system enter two times in an hook_node_presave?
I've write a simple module for my sites, where I populate a node reference by code.

I use hook\_node\_presave, but I notice that drupal enters TWO times in this hook, so if my node reference field is multiple, it populates it two times.

Is there something wrong on my code or is normal? In the presave hook I've to load another node and then save it

I have something like this:

```
   function alterator_node_presave($node) {
      if ($node->type == 'partner_progetto') {
        // here I load a node "progetto"
        // that is referenced on my partner_progetto node
        $progetto = node_load($node->field_progetto_rif['und'][0]['nid']);

        // here I load another node "soggetto"
        // that is referenced on my partner_progetto node
        $soggetto = node_load($node->field_soggetto['und'][0]['nid']);

        // then I've to fill a node_reference in the node $progetto,
        // using the nid of $soggetto
        $progetto->field_soggetto_ref['und'][]['nid'] = $soggetto->nid;

        node_save($progetto);
      }
   }

```

In this hook the system enter 2 times, so when I save a "partner progetto" node that has a reference to the node soggetto with nid '150' I've that the "progetto" node has this structure:

```
$progetto->field_soggetto_ref
  ['und']
    [0]['nid'] = 150,
    [1]['nid'] = 150;

```

The value of this field is filled two times.

# Answer
> 2 votes
Remove `node_save($progetto);` from `alterator_node_presave` and try. Because `hook_node_presave` is called just before the `node_save`. It can be reason of saving the field twice.

# Answer
> 1 votes
`hook_node_presave()` is invoked once for each node. As you implementation calls node\_save(), which then invokes `hook_node_presave()` again, your hook is invoked twice, once for each node.

Possibly, you could have an infinite loop, if `$node->field_progetto_rif['und'][0]['nid']` is the node ID of a node whose content type is "partner\_progetto"; be sure to avoid that.

Your code is the adding a new node reference all the times a node is saved, as you use `$progetto->field_soggetto_ref['und'][]['nid']`, and not `$progetto->field_soggetto_ref['und'][0]['nid']`.

---
Tags: 7, hooks
---


title: Cross domain ajax in a multisite setup

text:
# Question
Title: Cross domain ajax in a multisite setup
I have a drupal multisite install so that two sites can share the same codebase. In a custom module that both sites use, the ajax works on one site but with the other site it returns the error status 200. What my module does is that it creates a new "article" node programmatically.

I read somewhere that this is a crossdomain ajax problem, even though both sites are really on the same hard drive of the same server.

The views module, which also uses ajax, works on both sites with no problem.

How can I make the ajax work? I'll give up the multisite way if it creates more problems than it solves

Update: here is the jquery code :

```
(function ($) {
    Drupal.behaviors.addArticle = {
        attach: function (context, settings) {
            var addstuffAjaxLink = $(".addsomething");
            addstuffAjaxLink.click(function(e) {
                var ajaxpath = 'addstuff/ajax';
                $.ajax({
                    type: "POST",
                    url: ajaxpath,
                    data: {'from_js': true},
                    dataType: "json",
                    success: function (data) {
                        if (data.message) {
                            var message= data.message;
                            alert(message);
                        }
                    },
                    error: function (xmlhttp) {
                        alert('An error occured: ' + xmlhttp.status);
                    }
                });
            });
        }
    };
})(jQuery);

```

and this is the custom module php code:

```
<?php
/**
 * Implements hook_menu().
 */
function addstuff_menu() {
  $items = array();

  $items['addstuff/ajax'] = array(
   'title' => 'Add Stuff',
    'page callback' => 'addstuff_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}
/**
 * Menu callback.
 */
function addstuff_callback() {
    if ($_POST['from_js']) {
        global $user;

        $newnode = new stdClass();
        $newnode->uid = $user->uid;
        $newnode->name = $user->name;
        $newnode->language = LANGUAGE_NONE;
        $lan=$newnode->language;
        $newnode->status = 1;
        $newnode->promote = 0;
        $newnode->sticky = 0;
        $newnode->created = timestamp;
        $newnode->title = 'New Article';
        $newnode->type = 'article';

        $newnode->field_body = array(
            $lan => array(
                array(
                    'value' => 'Click HERE to add some text.',
                    'format'=> 'full_html',
                    'safe_value' => 'Click HERE to add some text.',
                )
            )
        );
        node_save($newnode);
        $response = array(
            'message' => 'Article Created',
        );
        return drupal_json_output($response);
        exit;
    } else {
        $response = array(
            'message' => 'There was an error',
        );
        drupal_json_output($response);
        exit;
    }
}
/**
 * Implements hook_init().
 */
function addstuff_init() {
  drupal_add_js(drupal_get_path('module', 'addstuff') . '/addstuff.js');
}

```

# Answer
> 2 votes
The first thing I'd probably do is to change the `url` option of `$.ajax` to something like:

```
$.ajax({
  // your code goes here
  url: Drupal.settings.basePath + 'addstuff/ajax',
  // more of your code goes here
});

```

So, what could be happening (assuming of course, that you have clean URLs enabled on both sites) is that when you are on a page on your site with the Drupal path, say, `node/add` and click on your link, the AJAX request to `addstuff/ajax` without the leading slash (base path) goes to `node/addaddstuff/ajax` which will return HTML and not JSON as expected. Hence, jQuery throws a `parseerror` and Drupal calls its error handler. You can check this by inspecting the XHR requests being sent out from the *Network* tab of your browser's developer console.

However, this doesn't explain how your code works as expected on one site but not the other.

---
Tags: ajax, multi-sites
---


# Question
Title: Views Exposed TID Filter Hidden Behind Body
Hello i have an exposed filter on my view allowing folks to seach by term. When folks start typing though only the first option on the list is shown and he rest is hid behind the body of my website.

You can view it here- my exposed filter

Its the 2nd from the left in the red bar view up top.

Its driving me mad.

thanks

# Answer
> 1 votes
Looks like it is just a minor problem with the `overflow` property of the parent element. The following CSS rule (specific to your page) should fix it:

```
#preface-top.row,
#block-views--exp-latestnew-page_1.block {
  overflow: visible;
}

```

---
Tags: theming, views
---


# Question
Title: manually adding terms to nodes directly from db
I have lots of nodes in my system. I want to add them some taxonomy terms.

I have a CSV file for each term, and in this file I have the list of node id's. Example:

apples.csv:

5 9 12 24 .... ....

SO I need node 5, 9, 12 and 24 to have the term "apples".

I wrote a php script to directly add that term to each of the nodes. That script populates the table "field\_data\_field\_category" correctly.

I can also see the term on the node page.

The problem is the nodes dont appear in the term page. Also if I create a view to display nodes of specific term, it becomes empty.

Is there another table to keep the node - term relationship?

EDIT:

I just found that there is another table keeping the relationship between node and term: taxonomy\_index: "Maintains denormalized information about node/term..."

How does this table populated? On a cron run? Because I see some of my node - term pairs there. Some not.

# Answer
You may use the Feeds module to update all your nodes with new terms.
> 0 votes

# Answer
From the Views query output, I see:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, node.sticky AS node_sticky, 'node' AS field_data_field_based_on_node_entity_type, 'node' AS field_data_body_node_entity_type
FROM
{node} node
WHERE (( (node.nid IN  (SELECT tn.nid AS nid
FROM
{taxonomy_index} tn

```

I see views is using taxonomy\_index table, so I ended up populating this table also. Here is my code if anyone is interested:
> 0 votes

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


# Question
Title: How to make a responsive theme in Zen 5? Modules and procedures to keep or to leave from older Zen versions
I'm using Zen theme back from 2007, when Drupal 5 comes out (anyone remembers those subtheme directories put into the main zen directory?). Thanks to this theme reliability and awesome community, the small team I work in completed several projects for customers in Drupal 5, 6 and 7. Since the theme base is standard, projects change hands smoothly and common solutions were standardized internally.

Now, customers start to get more demanding about mobile devices and building a separate theme or a simple alternate stylesheet for mobiles is not enough anymore. "Responsive" become a term used by the marketing people too. And here starts our problems as developers.

A video from July 2012 by Palantir is a good starting point, and the Responsive web design handbook is extensive. Maybe, too extensive. The number of new concepts is overwhelming (to me).

Compass, SASS, the use of a Ruby CSS preprocessor (compass) running as a server to generate CSS files from SASS, and not to improve loading times by the client are some of the new *design* concepts implemented through Zen Grids. Respond.js and HTML5 shim seems to be new *retrocompatibility* concepts. Zen Grids seems to be able to do most of the work Panels and templates used to do.

Anyone here started from a previous Zen theme and set of tools like view blocks, Panels and Mini panels, field templates, conditional stylesheets and now have *successfully* changed the working method to adapt to Zen 5 new features? What should I keep and what should I have better to forget after entering in the Zen 5 world? Here some tools that seems to make obsolete some old companions:

* Field / view field templates \> Fences?
* Panels \> Zen grids?

How blocks and views will adapt in this new approach, looking for responsiveness? How navigation? I used awfully a lot Menu Block and now I see responsive menus like this popping out. Conditional stylesheets are something I can forget of because of Compass? How can I adapt user-loaded images through IMCE / TinyMCE?

I don't want to use old, unfit tools in a new environment, so what's the best, practical approach while selecting modules and designing the theme from a "old school" Zen enthusiast point of view *in your experience*? Priorities for my team is to keep low the number of contrib modules and identify a standard process to create quickly complex responsive layout for nodes and for views keeping code as clean and maintainable as possible. Thank you very much.

# Answer
I would avoid getting confused. Zen Grids is not the same as the panels module. The fences module just makes it easier to override the default field html output. The responsive menu you showed is just css and a media query.

A little zen might help also, take a deep breath and repeat after me, "It is all just css."
> 0 votes

---
Tags: blocks, panels, theming
---


title: Creating a block in own module

text:
# Question
Title: Creating a block in own module
I am using Drupal 6.27, created my own module, used hook\_perm() in my module. Now the question is - did i do that in the right way?

```
/**
 * Implementation of hook_block().
 */

function adminka_block($op = 'list', $delta = 0, $edit = array()) {
  switch($op) {
    case 'list':
      return array(
        'adminka_simple_block' => array('info' => 'adminka simple block', 'cache' => BLOCK_NO_CACHE),
      );
    case 'view':
      switch($delta) {
        case 0:
          if (user_access('view adminka')) {
            $block['subject'] = t('My admin panel');
            $block['content'] = '<a href="/node/add/' . variable_get('content_type', false) . '">Добавить ' . variable_get('content_type_name', false) . '</a><br />';
            $block['content'] .= '<a href="/logout">Выход</a>';
            break;
          }
      }
      return $block;
  }
}

```

Because i didn't found another way to restrict that block visiblity only to users with user\_acess('view adminka').

# Answer
> 1 votes
I think you do it in the right way, but instead of using this

```
$block['content'] = '<a href="/node/add/' . variable_get('content_type', false) . '">Добавить ' . variable_get('content_type_name', false) . '</a><br />';
$block['content'] .= '<a href="/logout">Выход</a>';

```

you should use l function

> This function correctly handles aliased paths, and adds an 'active' class attribute to links that point to the current page (for theming), so all internal links output by modules should be generated by this function if possible.

like this:

```
$block['content'] .= l(t('Выход'), '/logout');

```

# Answer
> 0 votes
Regarding perms, yes, you are doing that part right. However, I *think* the `$delta` case value in your view should be `adminka_simple_block` not `0` and this is why I like to set up blocks like this instead because of the ease of adding more as your module gets bigger....

```
function adminka_block($op = 'list', $delta = 0, $edit = array()) {

  $blocks=array();

  switch($op) {

    case 'list':

      $blocks['admin']['info'] = 'adminka admin block';
      $blocks['admin']['cache'] = BLOCK_NO_CACHE;

      $blocks['another']['info'] = 'adminka another block';

      return $blocks;

    case 'view':

      switch($delta) {

        case 'admin':

          if (user_access('view adminka')) {

            $blocks['subject']  = t('My admin panel');
            $blocks['content']  = l('Добавить ' . variable_get('adminka_content_type_name', NULL), 'node/add/' . variable_get('adminka_content_type', NULL));
            $blocks['content'] .= l('Выход', 'logout');

          }

          return $blocks;

        case 'another':

          $blocks['subject']  = t('Another Block');
          $blocks['content']  = 'Here we have another block';
          $blocks['content'] .= ' with more content, etc...';
          $blocks['content'] .= ' with default caching.';

          return $blocks;

      }
   }
}

```

I will admit I am *not* up on translation stuff, but I think you may want to think about using `t()` to do more here, but that's a whole nother ball of wax :)

---
Tags: 6, blocks
---


# Question
Title: How do I add embedded YouTube videos in a field?
I would like to have a field for adding YouTube videos; however, I do not want to use the Media module because it is very buggy at this point. Is there any alternative for Drupal 7?

# Answer
> 3 votes
In Drupal 6, you would use Embedded Media Field (emfield) to do this, but that module is being replaced with Media module in D7. Some people are arguing that emfield should be ported to D7 for the time being, until Media reaches a stable version.

An interesting workaround is that of the Vimeo Link Formatter module, which is a formatter for the link field provided by Link module. If you can write php, it might not be too hard to alter that module and make a youtube-equivalent for yourself (and maybe the rest of the community).

# Answer
> 8 votes
Just use the Video Filter module, here is a quote from its project page:

> This is a highly flexible and easily extendable filter module to embed any type of video in your site using a simple token. Other modules can add video sites/formats (called codecs) using an easy plugin architecture.
>
> With WYSIWYG installed, you can use the Video Filter button to easily add videos in a rich text editor.

# Answer
> 2 votes
What worked for me on D7 was the Video Embed Field. The media field was too complex, and emfield D7 port didn't work at all. The video filter mentioned above seems great but it doesn't provide a field, so it was not an option for me.

# Answer
> 0 votes
I'm having issues with the media - youtube module as well (D7). I think you could just create 2 fields: one for the youtube embed code and one for the youtube image thumbnail. Then show the thumbnail in the teaser display and the embed code in the full display.

---
Tags: 7, files
---


# Question
Title: Prevent JS from showing on specific pages
I've got a Javascript that I'd been able to post on every page using Drupal\_add\_js, and everything was fine till my client's needs changed.

Now I need to show that same JS script on every site page except one node type, and one specific URL and I dont know how to do this. I'd prefer to do it the Drupal way rather than use JS Injector if I can.

Any help is appreciated! Thanks Steph

# Answer
> 1 votes
Following your logic, something along the lines of...

```
$mgo=menu_get_object();
if ((isset($mgo) && $mgo->type=='TYPE') || $_GET['q']=='PATH') {
  ;
} else {
  drupal_add_js(...);
}

```

...where you are doing your drupal\_add\_js(...) should do it. I *think* this does it cleaner, but it's late in the logic day here:

```
$mgo=menu_get_object();
if ((isset($mgo) && $mgo->type!='TYPE') && $_GET['q']!='PATH') {
  drupal_add_js(...);
}

```

ADDITION:

```
$mgo=menu_get_object();
if (isset($mgo) && $mgo->type=='products') || strpos($_GET['q'], 'user/preference_center/ratings_reviews/')===0) {
  ; // do nothing
} else {
  drupal_add_js(....);
}

```

will add js only if you are not looking at a product node or not in a path that starts with user/preference\_center/ratings\_reviews/ BUT please note that if what is after user/preference\_center/ratings\_reviews is a node, this won't work because that path is actually node/#, so you will have to then do...

```
$mgo=menu_get_object();
if (isset($mgo) && $mgo->type=='products') || strpos(drupal_get_path_alias(), 'user/preference_center/ratings_reviews/')===0) {
  ; // do nothing
} else {
  drupal_add_js(....);
}

```

..instead.

# Answer
> 0 votes
I just started working with JS & Drupal, but this might work: If you put it in the the template.php under the the YOURTHEME\_preprocess\_node() you can do something like:

```
<?php
$node = menu_get_object();
  if (isset($node))
  {
       if ($node->type = 'THENODETHATDOESNTNEEDIT')
       {
       //Do some stuff
       }
       else
       {
       //ADD YOUR JAVASCRIPT HERE
       }
  }
?>

```

This should drop Javascript only into the nodes you want...

---
Tags: 6, javascript
---


# Question
Title: How should I file an issue on drupal.org that affects multiple modules?
I have an issue that is caused only when three modules are enabled together (logintoboggan, pathauto, and entity). When I upgrade entity from rc1 to rc3, one of the functions of logintoboggan breaks if pathauto is enabled. I have attempted to determine which module is interfering with logintoboggan, or if it in fact is logintoboggan itself that is at fault, but this exceeds my debugging ability.

So, in cases where one has an issue where a specific combination of modules causes an error, where should the issue be filed? Should only one issue be filed, or should multiple issues be filed and linked to one another?

# Answer
> 3 votes
Personally, I would pick the one with the highest level (or least mature), and post in that issue queue. By highest level, I mean the one closest to the user, the one with the modules dependent on it, etc. In your case, I think logintoboggan would be most appropriate.

Then in the issue, explain the situation in detail and mention the other modules.

If the project owner thinks a lower level module is the culprit, then they will decide what to do. More than likely, they will post a comment, and reassign to a new queue.

I would not post the issue in multiple queues, though. It makes tracking things too hard.

---
Tags: 7, debugging, community-official-site
---


title: Distance to shop long/lat

text:
# Question
Title: Distance to shop long/lat
I want to create a filter where companies are able to find users within eg. 10 kilometers using users added long/lat and the company's long/lat they have added.

I am using geolocation but how am I going to go about this?

# Answer
As Jimajamma pointed out, the Location module along with Views will allow you to filter by distance. I am currently using zipcodes to filter by, but one could do geocoordinates as well.

Here is a step by step article on how to achieve filtering. Although the article is a tad old, it is still relevant and can easily be adapted for drupal 7.

http://drupal.org/node/359463
> 1 votes

---
Tags: views, location
---


# Question
Title: How to pass variables between theme functions
I often use functions that contain variables in the following files:

* Template.php
* Custom Panels Style Plugins
* node.tpl.php files
* field.tpl.php files
* views.tpl.php files

I often needed to pass variables between these functions.

At the moment, I do this by declaring my variable as a global Using PHP's global command. However, I have read that is not best practice. Is there a better way?

I know that Drupal has variable\_set() and variable\_get(). However, apparently these have similar problems to using Globals for lots of little variables.

# Answer
> 3 votes
I am newish to Drupal, but will give this a shot (I'm sure someone will tell me if I am wrong).

You can set variables that exist in different contexts by using the `template.php` file of your theme by adding stuff to the `$variables` array with preprocessor functions. So you could maybe add your variables to the `YOURTHEME_preprocess_html()` function, which should make them available everywhere.

```
function YOURTHEME_preprocess_html(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');
}

```

# Answer
> 0 votes
What about hook\_preprocess? This hook called for all templates.

# Answer
> -1 votes
You probably need some settings, so using variable\_set is a normal practice I think.

---
Tags: theming
---


# Question
Title: How to get the attachment display of a view to show up in a PDF display (created using Views PDF module)?
I have a view with the following displays in a single View on my Drupal 7 website:

* Page
* Attachment 1
* Attachment 2
* PDF

The Attachment 1 and 2 displays both are set to be shown on the Page display, based on contextual filters and relationships. This is working great, but I'm not sure how to include all fields from the Page as well as the fields from the Attachments when creating the PDF display (using the PDF Views module), since they are all part of the same View. Is it possible to do so?

# Answer
I never was able to get the Attachments to show up in the PDF, but here is my workaround:

I was able to get the output that I needed by using the Reference module and the Viewfield module.

1. Created Content type A and content types B, C, and D. B, C, and D are all associated with Content type A via Reference fields.
2. Created contextual/relationshipped views for B, C, and D, relating it to the title field of Content Type A.
3. Created a Viewfield on Content Type A for each of the sub-content types (B, C, and D).
4. Created a View for Content Type A, contextualized with Content:Title, and added the Viewfields to this new View (using reverse relationships with the node referenced field). I then added a PDF Page view using Views PDF, and that did the trick!

I can provide more detail if needed. Just let me know...
> 2 votes

---
Tags: views, files, log-messages
---


# Question
Title: Showing content of subterm under parent term
I have following taxonomy structure

```
parent-A
    subterm-1
        sub-subterm-a
        sub-subterm-b
    subterm-2

```

how can I show contents of both the sub-subterm (a and b) when i select/click subterm-1 ; and contents from subterm-1 (sub-subterm a+b) and from subterm-2 when I select parent-A using views - block display

# Answer
> 0 votes
This may not be the most standard way of achieving it but it may help in your case. Just try the following code by replacing 24 with a $termid that exists in your case. And see if this gets your work done.

```
    //to get the children of a taxonomy term
    //lets take 24 for example

      $terms = taxonomy_get_children('24');

      //to get the nodes associated with a termid

     foreach ($terms as $term) {
         $termnodes = taxonomy_select_nodes($term->tid);

         foreach ($termnodes as $termnode) {
              $node = node_load($termnode);
              $node_output = node_view($node);
              print render($node_output, $view_mode = 'teaser'));
        }
  }

```

---
Tags: views
---


# Question
Title: Show page with child terms when clicking parent term
I have a vocabulary with the following structure:

```
Vocabulary
Parent term 1
    Child term 1.1
        Node tagged with child term 1.1
    Child term 1.2
        Node tagged with child term 1.2
Parent term 2
    Child term 2.1
        Node tagged with child term 2.1
    Child term 2.2
        Node tagged with child term 2.2
Parent term 3 (no children)
    Node tagged with parent term 3
    Node tagged with parent term 3

```

With very limited knowledge I managed to create a view displaying the top-level terms. I would like to click on one of this terms and go to a page displaying either the child terms of the selected parent or, if there are no children, the nodes tagged with that term. After much trial and error all I get when clicking a parent term is a message of 'There is currently no content classified with this term' when I really want to display its children.

In a desperate attempt I created different vocabularies for the terms with child terms and the terms with just nodes underneath. Then I used Views to create different blocks based on the vocabulary name and placed those blocks using the Context module, but this seems like a long shot and I'm sure there's a more straightforward way to accomplish this. By now I have tried several combinations with Taxonomy Menu, Taxonomy Display, arguments and relationships in Views, etc. and I'm not any nearer.

I posted this at the Drupal forums but with no luck yet, I hope someone here can help me figure this out :)

# Answer
Follow these steps

1. Create a view
2. Add a relationship "Content: Tags", (Tags is vocabulary name I want to show content for)
3. Add a contextual filter "Content: Has taxonomy term ID (with depth)" (you can provide a depth of taxonomy term here to display content, if set to 0 it will show content tagged with that particular term id only, if 1 then that particular term id + its first child term content)
4. And provide proper value for this contextual filter.

Here is the screenshot of view I've created:

Hope this helps.
> 0 votes

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


title: How do I add a more/less link in block?

text:
# Question
Title: How do I add a more/less link in block?
How do I add a more/less link to drop-down and roll up a block?

I have a custom search block with a lot of field items and as such, the block is so long.
I want to be able to add a more link to drop down the redundant fields and less to roll up the block again.

I'm trying to do something similar to the search block on checki.com.ng. I am running a Drupal 7 site, naijabooker.com.

# Answer
I assume you have a custom block with a form created from your custom module.
You would need to add an attribute `#prefix` to the first field item starting from which you want to hide the items and add an attribute `#suffix` to the last field item you want to hide, For example,

```
$form['first_item']['#prefix'] = '<div id="accordian">';

// more elements here

$form['last_item']['#suffix'] = '</div>';

```

Then, you can bind `jQuery.slideUp()` and `jQuery.slideDown()` to the more/less link element, let's say for example, `#moreless`.

```
$('#moreless').bind('click', function(){
    if( $('#accordian:visible').size() ){
         $('#accordian').slideUp();
         $(this).html('More »');
     }else{
         $('#accordian').slideDown();
         $(this).html('Less «');
     }
});

```

You can see the working jQuery code here. These two jQuery functions are provided by jQuery core API. You don't need to include any extra library.
> 0 votes

---
Tags: 7, blocks, search
---


# Question
Title: How do I display/edit the machine name for a View?
How do I display/edit the machine name for a View?

Reason for asking is that I tried cloning a view but the name I gave was rejected because it had already been used but I couldn't see where.

# Answer
> 17 votes
You can export view, change values, delete original and import view back.

There is a import option in the views listing page. Just paste this url after your current url and you will see the import views page. By seeing your tags I am assuming you are using Drupal 7, so the given below url will work only for Drupal 7.

Below is the url to be added :

```
#overlay=admin/structure/views/import

```

**To export view:**

1. go to /admin/structure/views
2. under 'operations' column click on arrow and select 'export'
3. copy code and edit/change in external editor
4. go to /admin/structure/views/import and import changed view You can first delete existing view or select 'Replace an existing view if one exists with the same name' on the import settings –

# Answer
> 9 votes
I don't think you can change the machine name of a view, at least not in the UI. You can see the machine name in the URL if you mouse over the "edit link".

# Answer
> 6 votes
You can clone it with the new machine name.

**Update:** How to display the machine name for a View.
You can see list of all views in your Drupal installition using this code:

```
$views = views_get_all_views();
// Optional: views objects are big so unset large members
foreach ($views as $machine_name => $view) {
  unset($view->display, $view->localization_plugin);
  $views[$machine_name] = $view;
}
// Print array keyed by views machine name
dpm($views);

```

You can run this code on page `devel/php` (needs Devel module).
There will be printed array of views keyed by machine name and you will be able to find your lost view.

**Update:** You can search views by machine name at views list page in Drupal 7. For this you should turn on flag "Show filters on the list of views" in Views settings.

# Answer
> 4 votes
`$page["#views_contextual_links_info"]["views_ui"]["view_name"]` \- By using this variable you can get the machine name of your view.

# Answer
> 0 votes
You can change the **value** of the **name** field in the **views\_view** table in the database. Not always the best idea, since you can end up breaking references to the blocks/pages in parts of the site, such as in panels.

# Answer
> 0 votes
I don't believe you can change the machine name of a view once you've created it and finding the machine name is not at all intuitive. I imagine this may be because the only people who would be needing the machine name would be programmers and fairly advanced power users who can handle some obfuscation to make the interface easier to understand for everyone else.

To find the machine name of the view, just go to your views list and hold your mouse over any part of the row. It doesn't have to be the edit button. This is not an official JavaScript mouseover so your browser may choose to render it in a different way than I'm seeing or perhaps even not render it at all. In those cases, you can peek at the HTML source and you'll notice that in the tag of the view row that you're looking at, there's a title attribute that will read something like .

If you want the machine name of a display inside the view, that's a little easier. That's in the Advanced block of the views edit interface. It's in there somewhere and it's labeled as "machine\_name" so there aren't any special tricks to uncover it. Unlike the view's machine name, you can change this one.

So what do you do if you need to change the machine name of the view? Well, you could get crunchy with the database and manually edit it to update the machine name everywhere that it's used, but this is too much trouble in my opinion. There's a far easier way. Just clone your view and give it the machine name you really wanted. After it's cloned, you can delete the original one that had the wrong machine name.

---
Tags: 7, views
---


title: Omega Layout Configuration

text:
# Question
Title: Omega Layout Configuration
I'm new to Drupal and Omega theme. I made a subtheme of Omega 3.x HTML 5 using Omega tools.

I need to configure zones and regions in theme settings, Thus i went Home » Administration » Appearance » Settings (on my subtheme) \> Zone and region configuration.

But those zones are not configurable. and I cannot click on those. Where did i do the mistake ?

# Answer
Solved: It was a Javascript/jQuery conflict.
> 0 votes

# Answer
I'd go in with firebug and check first that those collapsible blocks contain the HTML form content you expect to be there and that it is simply hidden by CSS rule(s). Then if that is true then edit the CSS for those collapsible blocks to make them able to dismay content. If there is no form content there then possibly could be a permissions issue at a guess.
> 0 votes

---
Tags: theming
---


title: Allow commenting on front page?

text:
# Question
Title: Allow commenting on front page?
My client wants a comment section on the front page only. I can't figure out how to allow commenting on the front page. I tried allowing commenting on basic pages, but it wont show on the front.

Thanks.

# Answer
Excerpt from `modules/comment/comment.module` inside `function comment_node_view($node, $view_mode)`:

```
// Only append comments when we are building a node on its own node detail
// page. We compare $node and $page_node to ensure that comments are not
// appended to other nodes shown on the page, for example a node_reference
// displayed in 'full' view mode within another node.
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

```
1. commenting for the node must be turned on
2. The node must be shown in the `full`-view\_mode (normally this is `node/<nid>`)
3. `node_is_page()`: Whether the current page is the full page view of the passed-in node.
4. It must not be an edited preview of this node.

If you still feel like showing the comments on the frontpage for a specific node, try this:

```
$frontpage_commenting_node = node_load( **1** );
print render(comment_node_page_additions($frontpage_commenting_node));

```

Note: \- You need to change the parameter of node\_load to the effective node id in your system. \- This is for Drupal 7
> 0 votes

---
Tags: comments
---


title: Unable to compile css with Aurora

text:
# Question
Title: Unable to compile css with Aurora
compass watch

> > > Change detected at 02:13:25 to: style.scss error sass/style.scss (Line 20 of sass/partials/global/\_base.scss: File to import not found or unreadable: aurora/susy-grid. Load paths: /Applications/MAMP/htdocs/txmo/sites/all/themes/txmo\_aurora/sass /Users/davidfells/.rvm/gems/ruby-1.9.3-p362/gems/compass-0.12.2/frameworks/blueprint/stylesheets /Users/davidfells/.rvm/gems/ruby-1.9.3-p362/gems/compass-0.12.2/frameworks/compass/stylesheets Compass::SpriteImporter)

Running Ruby 1.9.3, latest versions of all gems freshly installed with JewelryBox. Other users on dev team are able to build this with matching gem versions.

# Answer
The problem turned out to be that the "aurora" gem cannot be installed alongside compass & compass-aurora for all this to work properly.
> 1 votes

---
Tags: theming
---


# Question
Title: is it possible to disable ckeditor for private messages?
I've ckeditor through out the site.But i don't need it for private messages(privatemsg module).Is their any way to disable CKeditor only for private messages?

# Answer
> 2 votes
check from settings or input formates

---
Tags: 7, wysiwyg
---


title: Content type issue

text:
# Question
Title: Content type issue
I'm building a Drupal 7 book listing website. I have created a content type called **book listing** and it has fields for book details and author details.

I want to be able to treat the author and book details as separate entity, in the sense that I want to have a views for author (and a special page for individual author) and book listing page with author name that links back to the author page. I have battled with this for over 3 weeks with no solution. I was thinking if there is a way I can load an author content type form on the book listing form.

I need help please. I found a question Content type within content type? which is similar to my case, but no detailed answer.

Thanks.

# Answer
> 0 votes
1. you have content type called : book listing.
2. Add field user reference if you want to treat author as user or node reference if you have author as content type.
3. Now on Book detail page give the link for author.
4. On author page if the author is user. call a view and display all the books along with other author information same you can do with node as well.

(There are many other way to do it but this one seems clean if you can separate author from book)

# Answer
> 0 votes
As you indicate in your question, you can use the Views module to pick individual fields from the database and create a "view" with those fields only. So you while you have a single entry form for both *Author detail* and *Book detail* you can use Views to separate the fields so that you can show *Author detail* without showing *Book detail*, and vice versa.

Views also let you create lists. With Views, you can, for instance, list authors and let each author name link to the full author description.

The learning curve for Views may be a bit steep, but once you master it, it is a very powerful tool to pull stuff from the database and customize the ways your site displays it.

# Answer
> 0 votes
Apparently, I can't comment yet (or don't know how to do it...). But perhaps the problem of authors appearing more then once can be fixed by going to the

views module --\> query settings --\> Check: "distinct" and "pure distinct"

Have you tried doing this?

---
Tags: 7, forms, nodes
---


title: change Your search yielded no results

text:
# Question
Title: change Your search yielded no results
I would like to set a custom message for my search using the core Drupal search module. Right now it says:

> Your search yielded no results
> Check if your spelling is correct.
> Remove quotes around phrases to search for each word individually. bike shed will often show more results than "bike shed".
> Consider loosening your query with OR. bike OR shed will often show more results than bike shed.

# Answer
The core Drupal search module uses several template files that dictate both how search results are displayed, and what's displayed when there are *no* search results.

If you're already using a custom theme on your Drupal site, the best way to customize those would be to copy and paste the entire 'search-results.tpl.php' file from the search/ module folder into your own custom theme subfolder.

Open that file up for editing and you'll see the following at the bottom:

```
<?php else : ?>
  <h2><?php print t('Your search yielded no results');?></h2>
  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

```

This is what's displayed if search results are not found (thus the 'else')... Modify the text to be anything you want here. The second line, which calls the search\_help() function is the one that displays the search suggestions. Feel free to replace that too....

And as always, before you can see your changes, you'll probably need to clear cache!

Let us know if this works for you!
> 4 votes

---
Tags: 7, search
---


# Question
Title: See all nodes where user profile entity reference matches the same entity reference on the node
I have the Profile 2 module where a user selects a zip code (which is an entity reference to the content type `ZipCode`)

The `ZipCode` content type has an entity reference to a `Region` content type.

Finally, there is a content type called Schools which has an entity reference to the `ZipCode` content type.

I would like to display all schools that match the region of the logged in user. Logically this means finding the user's region, and then all schools with the same region, through the zip code...

I can't for the life of me figure out how to do this. Any help would be appreciated.

# Answer
The easiest way is creating a view for the *School* content type and add the fields you want to display on your list. Then add:

1. A reference to the entity that is common between the *School* content type and the *ZipCode* content type. If there is no connection between the two, you will also need to add a reference to the *Region* content type and then to the *ZipContent* type.
2. Add an argument or contextual filter for the user ID of the currently logged-in user and limit the number of nodes displayed.

Note: I have sometimes achieved the same result by creating a view (for users) referencing the content types and adding the desired fields.

This is a video about view arguments: http://mustardseedmedia.com/podcast/episode39.
> 0 votes

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