# Question
Title: 'User Account' menu link does not show to anonymous users
When a user is logged in the User menu shows 'My Account' link and the 'Logout' link. However, when logged out the menu disappears.

How do I make a menu link to the user login page that only shows for anonymous users in the User Menu?

---

If Trey posted his comment as an answer, I would have checked it. I have disabled the block module since I use context. I created a second sitewide context that is triggered by the anonymous user role and placed the menu block with the link for login page in the user region. It works.

I still would like to see this accomplished in code. I tried to access the variables through preprocess functions but the menu links are already rendered by that time.

# Answer
That is a feature. An anonymous user doesn't have an account nor can he log out, why should there be links to these pages?

You might want to update your question to better explain what you actually want instead of explaining how it works right now :)

EDIT: To have a link to the Login page, just create a menu entry that points to /user/login. Just like /user/logout, this link will only be shown if you *can* log in (which means that you are not already logged in).
> 7 votes

# Answer
Check out the logintoboggan module; it provides a login block that works more as expected.

Or just go to your blocks, create a new block, and use the following code as block body:

```
<a href="/user">Sign In</a>

```

Use the following PHP code to determine the block visibility:

```
<?php global $user; return($user->uid == 0); ?>

```
> 1 votes

# Answer
The login links should appear when a user is not logged in. If you go to http://drupal.org, and you are not logged in, you will see the login link; once you are logged in, the login link is replaced by the logout link.

In fact, the following definitions are used for the "user/login" and "user/logout" menu callbacks:

```
  $items['user/login'] = array(
    'title' => 'Log in',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );

```

The first menu callback is not visible when the user logged in; the second menu callback is not visible when the user is not logged in.

Similar definitions are used in Drupal 6:

```
  $items['user/login'] = array(
    'title' => 'Log in',
    'access callback' => 'user_is_anonymous',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'file' => 'user.pages.inc',
  );

```

In both the cases, only when the access callback returns `TRUE` the link is accessible to the user; when the access callback returns `FALSE`, the link is not visible to the user.
> 0 votes

# Answer
This is not that complicated if you're trying to do this in Drupal 7 using the Bartik theme.

Create a user menu item and call it Login. Give it the link, user/login. It will automatically show up for anonymous users, and disappear for logged in users.

If you have problems with this, you may need to rebuild your permissions (on admin/reports/status page)
> 0 votes

---
Tags: routes, users
---


title: Custom Menu Form Node Creation

text:
# Question
Title: Custom Menu Form Node Creation
I have been going over posts and examples for hours but finally need specific help on where my code is broken. I'm trying to create link in navigation that opens a form to create a new node. However no link anywhere is being made and I'm not sure what is missing. While its supposed to also upload a image I'm not worried right now since it doesn't work anyway. As a beginner my module looks correct but experienced eyes can hopefully give me some advice on where I went wrong! Thanks for any support and let me know of anything else I can add to solve this problem.

```
<?php

function ImageLoader_menu() {
$items = array();
$items['ImageLoader'] = array(
   'title' => 'Image Uploader',
   'description' => t('Upload a image.'),
   'page callback' => 'ImageLoader_upload_form_submit',
   'page arguments' => array('ImageLoader_upload_form'),
   'access arguments' => array('access content'),
    );
  return $items;
}

function ImageLoader_upload_form() {
$form = array();

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => 'Name'
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create Node!'
);
return $form;
}

function ImageLoader_upload_form_submit($form, $form_state){
$node = new stdClass();
$node -> type = 'Nature';
$node -> title = $form_state['values']['name'];
$node -> language = LANGUAGE_NONE;
$node->path = array('alias' => '/');
node_object_prepare($node); // Set some default values.
$node->uid = 200;

$node = node_submit($node);
node_save($node);

drupal_set_message(t('Node Created'));
}

```

# Answer
> 0 votes
You should use below code in your code and clear the cache.

```
'page callback' => 'drupal_get_form',

```

---
Tags: nodes, forms, routes
---


# Question
Title: How to assign value from one file field to another programmatically?
I have a webform which have a file field. In the user profile I have also created a file field.

I am using the webform for user registration So I am assigning the values from the webform to the user profile fields programmtically on webform submit.

But I am unable assing the uploaded file in the webform to the user profile file field.

I am using the following code for assigning the file.

```
  $user->field_user_file['files']['und'][0]['value'] = $form_state['values']['submitted']['field_webform_file'];

```

but it did not work.

Any Idea what should I do for this?

# Answer
I have done it. Here is the code that I used to solved the problem.

```
  $file = file_load($fid);
  $user->field_user_file = array(
    'und' => array(
      '0' => array(
        'fid' => $file->fid,
        'filename' => $file->filename,
        'filemime' => $file->filemime,
        'uri' => $file->uri,
        'status' => 1,
        'display' => 1
      )
    )
  );

```
> 0 votes

---
Tags: 7, webforms, users, files
---


# Question
Title: How to setup the recipient email in the webform mail template file?
I have overridden the webform mail(webform-mail-19.tpl.php) template in my theme. The problem is I want to set the recipient in this template file so I used this code. `$email['email'] = 'example@example.com'` but it did not send email to this address instead it sends email to the email address which i setup in the email settings of the webform.

I print the `$email` array and I could see "example@example.com" email there but did not know why it sends the email to the default email address which is setup at the email settings of the webform.

Any Idea about this?

# Answer
> 0 votes
I have done it using hook\_mail\_alter

# Answer
> 0 votes
You cannot set the recipient in a template file, these files are only used for the theme layer. The templates only control the display of information.

The recipient email must be set on the settings page of the webform.

# Answer
> 0 votes
You can implement following step for the mail setting.

* Add a hidden component in the webform.
* In the webform mail setting page, you can set hidden component as mail to address.
* You can override the value of hidden component in webform mail template.

---
Tags: 7, webforms
---


# Question
Title: Attaching a view to a content type that takes the content type's taxonomy terms as arguments
What I am trying to do is create a content type with a taxonomy vocabulary field. When creating the content type and selecting one or more of the terms, I would like the content type with an attached view to render the node with a list of nodes (ex: teaser views) that share share the content type's selected taxonomy terms.

In the past I have used Insert Views and listed the taxonomy terms. I would like a more elegant solution so a user can just use a selection list or term radio buttons.

How would I go about attaching a view and passing the taxonomy terms of the content type to the "attached" view?

Thoughts?

Thanks.

Rich

# Answer
You can pass to the template, a variable which contains the second view value

```
function mymodule_entity_view($entity, $type, $view_mode, $langcode) {

  list($id, $rev, $bundle) = entity_extract_ids($type, $entity);
  switch ($bundle){
    case 'customtype':
      if( $view_mode == 'teaser' ){
        $entity->test['test'] = array(
          '#markup' => views_embed_view( 'view_2', 'default', $entity->field_custom['und'][0]['value'] ),
        );
      }
    break;
  }
}

```

Then, in your theme, a node--customtype.tpl.php, you can render the variable:

```
print render($test);

```
> 0 votes

---
Tags: views
---


# Question
Title: Fields created by a Feature generated module remains after disabling the module
In **my-site-com** I created a new feature to show the component: **fields** , then I added some fields, I download the feature as a module called **my-feature-module**, then I saved and enabled this module in other drupal installation **my-site-2.com**.

I get all the fields properly. So far so good.

Now I disabled the module **my-feature-module** in **my-site-2.com** and the problem is that the fields are not removed, they remain there. Is this normal? I mean, expected the fields to disappeared if I disable the module.

I make sure I cleared all caches and updated database, just in case it was a cache problem, but problem still persist.

# Answer
Yes, this is normal. Some configuration items such as views can be implemented purely as code and some such as fields require database updates. Items in the former category will be removed when you disable a feature, those in the latter category will not. This is not necessarily a good thing but once you understand it, at least you know how to deal with it (manual removal of items).
> 0 votes

---
Tags: features
---


title: Add options to dropdown with ajax

text:
# Question
Title: Add options to dropdown with ajax
I am trying to use ajax in my form to dynamically add options to the dropdown, with the click of a button. The value entered in the textbox must be added to the dropdown. However i am not sure how to retain the added values in the dropdown. Currently only the recently added value remains in the dropdown.

This is my module code:

```
<?php
function dropdown_menu(){
    $items['dropdown_form'] = array(
        'title' => 'Dynamic Dropdown',
        'description' => 'adding more textfields',
         'access callback' => 'dropdown_access',
         'access arguments' => array(1),
        'page callback' => 'drupal_get_form', //used during form api
        'page arguments' => array('dropdown'),
    );
    return $items;
}

function dropdown_access() {
    return TRUE;
}

function dropdown($form, &$form_state, $no_js_use = FALSE) {
   $form['field_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Field Name:  String, Woodwind, Brass, Percussion'),
      '#required' => TRUE,
    );

   $field_val = isset($form_state['values']['field_name']) ? $form_state['values']['field_name'] : '';

  $form['add_to_dropdown'] = array(
      '#type' => 'button',
      '#value' => 'Add To Dropdown',
     '#ajax' => array(
      'event' => 'click',
      'callback' => 'dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
    );

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Dynamic Dropdown',
    '#prefix' => '<div id="dropdown-second-replace">',
    '#suffix' => '</div>',
    '#options' => get_dropdown_options($field_val),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#prefix' => '<br><br><div id="submit_btn">',
    '#suffix' => '</div>',
    );
    return $form;
}

function dropdown_callback($form, $form_state) {
    return $form['dropdown_second'];
}

function get_dropdown_options($key = '') {
  $options = array(
    t($key) => drupal_map_assoc(array(t($key))),
  );
  if (isset($options[$key])) {
    return $options[$key];
  }
  else {
    return array();
  }
}

function dropdown_submit($form, &$form_state) {
  print_r($form_state['values']); exit();
}

```

# Answer
> 1 votes
you should merge the existing vales in `$form['dropdown_second']['#options']` with the one in `$form_state['values']['field_name']`

something like this:

```
$existing_options = isset($form['dropdown_second']['#options']) ? $form['dropdown_second']['#options'] : array();
$new_option = get_dropdown_options($field_val);

$form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Dynamic Dropdown',
    '#prefix' => '<div id="dropdown-second-replace">',
    '#suffix' => '</div>',
    '#options' => array_merge($existing_options, $new_option),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );

```

---
Tags: 7, forms, ajax
---


title: Unpublish node based on field option

text:
# Question
Title: Unpublish node based on field option
Is there a way to unpublish a node if a user selects an option from a select list in field?

I have a field that has a list of cities. What I would like is if the user selects a certain city like London for example, the node is automatically unpublished so it can be moderated.

I have been trying with rules but every time I test my rule nothing happens so I'm sure there is something wrong with my rule or maybe there is an easier approach?

# Answer
You could also hook on hook\_node\_presave() and check here the value of the field... No ?

```
mymodule_node_presave($node) {
if($node->yourfield[.....]['value'] == 'London') {
$node->state = '0';
}
}

```
> 7 votes

# Answer
Did you test first to see if the "Entity has field" before doing the "Data comparison"?

When comparing fields it is necessary to first check that the entity has the field for Rules to pick them up. When comparing basic node attributes like Content Type you can omit this step.

Here's an example...
> 7 votes

# Answer
That can be done with some code in a custom module...

In the example below I'm assuming your content type is called article, and articles have a field called category, and when the category is Javascript then we unpublish the node.

First we need to modify the node form and add a new submit handler that fire after the one that saves the node (the order here is important):

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

```

Now we need to define our custom form submit handler:

```
function article_node_form_custom_submit($form, &$form_state) {
    // check if the category is Javascript
    if($form_state['values']['field_category']['und'][0]['value']=='Javascript') {
        // load the node
        $node = node_load($form_state['values']['nid']);
        // set the status to 0 to unpublish it
        $node->status = 0;
        // save the node
        node_save($node);
        // set a message to say what we've done
        drupal_set_message($node->title.' has been unpublished as the category was set to Javascript.');
    }
}

```

And that's all there is to it :)
> -1 votes

---
Tags: 7, entities, rules, workflows
---


# Question
Title: Comment/Node Body Fields Not Applying Filters
Hello ive been struggling for the past 24hrs getting my node body and comment body fields to use the text filters i have made. I wont go into the filter options just yet as the important thing here is that when i create a View html list with fields and Comment: Comment field, everything works well. I have paragraphs and my links convert so my text filters seem to be ok.

So i know its all to do with the Content Type's comment\_body Long text Text area (multiple rows) settings.

Filtered text (user selects text format) is checked. Text Fromat selected is my 'plaincustom' (originally plain text)

Web page addresses and e-mail addresses turn into links automatically. Lines and paragraphs break automatically.

All seem to be available. When i view my node or comment though i just get it all in one big blob of text with no paragraphs or line converts.

Can anyone suggest anything that could help solve this issue? I do not know if this previous question i asked about changing text formats has any relevance to this issue. thinkign about it it might have. Then why does my view show ok? Change Comment Text Format in phpmyadmin

# Answer
> 0 votes
my comment display was Plain Text.

---
Tags: input-formats
---


title: Unable to redirect after user_save

text:
# Question
Title: Unable to redirect after user_save
I am unable to redirect back to the page after executing the `user_save`. Following is my code snippet:

```
//if the response code is failed rollback the user changes and redirect
if ($results['code']!=200) {
  user_save(NULL,$account);
  drupal_goto("/admin/people");
}

```

# Answer
> 0 votes
Please check the below format:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'form_id_goes_here') {
    // Code here
    $form['#submit'][] = '_mymodule_test_registration_submit';
  }
}

function _mymodule_test_registration_submit($form, &$form_state) {
  // Code here
  $form_state['redirect'] = 'path1/path2/mypage';
}

```

---
Tags: users
---


# Question
Title: Changing the format of drupal pagers numbers
Currently the dupal pager displays numbers normally as 0 1 2 3 4, how do i change this format to something like 01 02 03 04

# Answer
> 1 votes
There is a theme\_pager function in drupal which help you to format pager. However i am not sure it can change the number from 1 to 01.

But, You can achieve this style with few lines of jquery. I am not proficient in jquery bu t a rough code is given below which may help you

```
(function($){
    function pad (str, max) {
        return str.length < max ? pad("0" + str, max) : str;
    }
    $( ".pager li" ).each(function( index ) {
         var number = $(this).text();
         if(number < 10){
           var new_number = pad(number, 2);
              if(($(this).attr('class')) == 'pager-item'){
                $(this).children().text(new_number);
              }else{
                $(this).text(new_number);
              }
          }

    });
})(jQuery);

```

The output

---
Tags: paging
---


# Question
Title: Conflict with db_set_active and variable_get
I am running a drupal multi-site system, with shared code and seperated DB. Each individual multi-site represents one continent and can have different language versions.

**What i want:** I am working on a module, that gathers all available languages on all multi-sites into one big continent/language map.

To query cross-multi-site data i use `db_set_active([multisite])` and manually fetch some data via `db_query()`.

```
foreach ($multisites as $multisite) {
  db_set_active($multisite['db']); //switch context
  $links = db_query(Select language from {languages} etc...)) // run query
  do_somthing_with_data($links) //work with data
  db_set_active(); //switch to default
}

```

This works pretty fine, but there are already drupal-core functions in `language.inc` i want to use (e.g. `language_negotiation_get_switch_links()`).

```
foreach ($multisites as $multisite) {
  db_set_active($multisite['db']); //switch context
  $links = language_negotiation_get_switch_links(...,...) // run core-function
  db_set_active(); //switch to default
}

```

**Here is my problem:** Several core functions use `variable_set()` and `variable_get()`. They are persistent and initialized on bootstrap.

When changing the active database with `db_set_active()`, incoming queries have the new context, but values fetched with `variable_get()` are inconsistent, because they store data from default database, filled on bootstrap.

**In a nutshell:** I want to run core-functions on one multi-site with data from another multi-site. `db_set_active()` works fine, but data is inconsistent because `variable_get()` uses data, which is initialized on bootstrap.

Has anyone ever worked with this issue?

Kind regards larry

**Addition:**

As I got deeper into development it became more and more complicated. I don't recommend the procedure of cross-multi-site-core-function-calling, because the initialization of core-functionality is triggered during bootstrap.

Here an example:

The multi-site you are browsing to does not need to initialize language.inc, because it has just one language-version. Further in code-progress you switch context to a multi-site with two or more languages but language.inc functionality is not available, because it was not initialized.

# Answer
> 5 votes
I've been reading around, and on `db_set_active` API page on d.o the 2 comments on that page mention the problem with caches and multi dbs.

So I went on to look at `variable_get` API page and it uses `global $conf` variable. I did a quick search on google on how to "refresh global variables conf" and got this page on d.o `DrupalWebTestCase::refreshVariables()`. Basically this function refreshes the global variables like so:

```
protected function refreshVariables() {
  global $conf;
  cache_clear_all('variables', 'cache_bootstrap');
  $conf = variable_initialize();
}

```

So I'm guessing (I haven't tried it and I don't have a multisite installation at hand to test it) you just need to utilise the code from the above function and clear the variables cache and re-initialize the variables in your foreach loop. I'm not sure how efficient it is so that's another issue if it's not efficient and slows down your page.

```
global $conf;
foreach ($multisites as $multisite) {
  // Not sure if cache_clear_all should be called before or after switching the database. You should test and figure out what's best.
  cache_clear_all('variables', 'cache_bootstrap');
  db_set_active($multisite['db']); //switch context
  // Re-set $conf global variable so when variable_get gets called it uses the updated $conf.
  $conf = variable_initialize();
  $links = language_negotiation_get_switch_links(...,...) // run core-function
  db_set_active(); //switch to default
}

```

Hope this helps steer you in the right direction. Good luck

---
Tags: database, i18n-l10n, multi-sites
---


title: How to group by with rollup?

text:
# Question
Title: How to group by with rollup?
How to get booking records from booking table? How to get `GROUP BY` function `WITH ROLLUP`?

Here is my SQL query:

```
SELECT * FROM booking
GROUP BY startBooking WITH ROLLUP;

```

How to convert above query in Drupal 7?

```
     $queryPrice = db_select('booking', 'b');
     $queryPrice->fields('b');
     $queryPrice->groupBy('b.startBooking');
     $resultPrice = $queryPrice->execute();

```

How to roll up use in above query in Drupal 7?

# Answer
> 2 votes
You can add a `GROUP` modifier right to the end of the string:

```
$queryPrice->groupBy('b.startBooking WITH ROLLUP');

```

With the rest of your query Drupal produces:

```
SELECT  b.*
FROM
{booking} b
GROUP BY b.startBooking WITH ROLLUP

```

---
Tags: 7, database
---


title: What does the menu_masks variable do?

text:
# Question
Title: What does the menu_masks variable do?
When I was building a feature (as in Features), I noticed the menu\_masks variable. I have read menu\_get\_ancestors() and \_menu\_router\_save() but I still don't understand what it does.

On a more practical level: When I'm building a feature which defines the menu's for my site, should I export the menu\_masks variable too?

# Answer
> 6 votes
*menu\_masks* is a Drupal variable used to find the possible ancestors of a menu item. It contains an array of values that are calculated from the paths defined from modules; each values is essentially a binary number where the digit is 1 when the path part doesn't contain a placeholder, and 0 when it contains a placeholder. For example, the number for node/%node/edit is 9 (101 in base 2), while the number for admin/structure/types/manage/%comment\_node\_type/comment/fields is 123 (1111011 in base 2).
The reason why numbers are used is avoid comparing strings; plus those numbers are easily sorted in a way that a number matching a path without placeholders is placed before a number matching a path with one or more placeholders. (The number for %/%/% would be 0, while the number for admin/appearance/list is 13.)

Notice that `menu_get_ancestors()` doesn't return the ancestors of the path passed as argument, but the possible ancestors. Passing `array('node', '12', 'edit')` to the function, I would get the an array containing the following values, as result.

1. node/12/edit
2. node/12/%
3. node/%/edit
4. node/12
5. node/%
6. node

In my test site, only the third, the fifth, and the sixth are paths defined by the modules I installed.

You don't need to export the *menu\_masks* variable: Its content is very specific for the site and it is re-calculated when `menu_rebuild()` is called.
Drupal is still able to work correctly even in the case `menu_rebuild()` is not yet called, and that Drupal variable has not been set. You should not notice any performance issue, but if that would be the case, you can call `menu_rebuild()` or force Drupal to call that function; if you have the Devel module installed, you can easily force Drupal to rebuild its menus.

---
Tags: 7, routes, features
---


title: Session breaks Entity API

text:
# Question
Title: Session breaks Entity API
Whenever I try to use $\_SESSION or variable\_set it breaks the Entity API. It says

> "Fatal error: Call to undefined function entity\_get\_info() in mydrupal\sites\all\modules\entity\includes\entity.inc on line 55"

And then I have to reinstall the entire website because this fatal error shows up on every page. So I can't even access any of the adminscreens or anything to uninstall the modules or anything.

Does anybody here know if this is just a bug or am I doing something wrong? I was just filling the session with an entity.

# Answer
Variables are serialised (as are session writes as I understand it), and complex objects like entity API entities don't serialise well.

The better solution would be to store the entity type and ID in the session, then load it when reading:

```
$_SESSION['saved_entity'] = array('type' => 'node', 'id' => 1);

...

$saved_entity = entity_load($_SESSION['saved_entity']['type'], array($_SESSION['saved_entity']['id']));

```

And do the same thing for the variables.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Can anyone recommend a good Drupal module for managing/displaying videos
I would like to put together a video gallery on my website and am wondering if there are any existing Drupal modules to manage that. I'm using Drupal 6 and most likely the videos will be hosted on YouTube.

Ideally, I would like to arrange them in topical albums in which each video could be annotated with a description of the videos.

Thanks.

# Answer
> 7 votes
Drupal 6: Embedded Media Field. Now has a D7 version too.

> This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.

Drupal 7: Media

> The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.

# Answer
> 1 votes
The simplest modules to do this task are:

1. IMCE : IMCE is an image/file uploader and browser that supports personal directories and quota.
2. WYSIWYG : Allows to use client-side editors to edit content.
3. CKEditor - WYSIWYG HTML editor: loads faster (the number of files has been reduced, so the browser will perform less HTTP requests) and developers friendly.

Adding content(videos) using these modules will be simple and later css modifications can help in the positioning and look of the gallery.

# Answer
> 1 votes
Actually, a most modern approach to do this in drupal 7 is Module Asset. It has his its own entity Media asset to manage the medias.

It's very flexible since you can create your own types of Media Assets, which are fieldable entities, and has integration with CKEditor module.

# Answer
> 0 votes
Use the combination of CKEditor and Media module.

**CKEditor:** It provides many HTML editing feature like:

1. Font formatting: type, size, color, style, bold, italic, etc
2. Text formatting: alignment, indentation, bullets list, etc
3. Cut and Paste, Undo and Redo
4. Link creation
5. Image insertion, with upload and server browsing support
6. Table creation and editing (add,delete rows, etc)
7. Right click context menus support
8. Complete toolbar customization
9. CSS support for a better integration in the web site
10. Lightweight and fast
11. For web developer it is easy to install and customize
12. For web users its simply easy to use!
13. Compatible with Internet Explorer 5+
14. Automatic browser detection and customization
15. Integration with ASP, ASP.NET and Javascript

**Media:** It provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site. It is a drop-in replacement for the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets.

---
Tags: files
---


title: how to refer to data of referenced node

text:
# Question
Title: how to refer to data of referenced node
In drupal 6, I have an event node type and an event\_attend node type.

The event\_attend node type has a nodereference to event. In hook\_form\_alter for the event\_attend node type, i added a validation routine.

In the validation routine, i would like to have access to the parent event node. I would like to compare event\_attend's date of participation to the date when the event is taking place.

Is there a way of doing this without doing a node\_load($nid\_of\_parent\_event)?

I was kind of hoping that somewhere in the $form variable lies data for the parent event's date but I think such is not the case. That is why I am posting the question here.

I am using openatrium 6x by the way. Anyway, I'll just make a query directly to the database to get the parent event's date using the event nid.

Thanks to everyone.

# Answer
> 1 votes
In drupal 6, the standard way of doing this is by using the following function:

```
node_load($nid = NULL, $vid = NULL, $reset = FALSE)

```

However if you want to implement it in Drupal 7, it becomes a lot easier using the Views and the References module. All you need to do is :

1. Create two different content types say a and b and add fields to them. You MUST add a node reference field(say to b)
2. A pop up would ask you to choose which node you would like to reference(choose a here) After that if you wish to look for some advanced settings, you can add Relationships depending on your requirement.

# Answer
> 0 votes
1.In Drupal 7,With the help of **Reference\**s module,you can refer one \**CONTENT TYPE to ANOTHER CONTENT TYPE.** 2.Suppose you want to refer second content type from first content type. 3.Then,while creating first content type,create a field of type NODE REFERNCE. 4.Then ,while creating the content,just add the second content type which u want to be displayed. 5.you can also link two content types with views using this REFERENCES module and by adding contextual filters and adding a relationship.

---
Tags: hooks, nodes, forms
---


# Question
Title: Unable to send email using "SMTP Authentication Support" module
I was working on a project where i used "SMTP Authentication Support" module to send emails. The authentications i provided were my personal gmail account details, It was working fine. Now when i am entering the site admins account details its displaying "Unable to send e-mail. Contact the site administrator if the problem persists." error. It also says that "SMTP Error: Could not authenticate." Can anyone let me where i am going wrong.

# Answer
> 0 votes
I would suggest you to use the module Mandrill

First you can go to mandrillapp.com and create an account.

After account creation go to Api and generate an Api key.

Then after installing the module on drupal instance. Go to Configuration-\>Mandrill-\>Add the Api key and your site is ready to send mails.

Hope this helps.

---
Tags: 7, emails
---


# Question
Title: Can i get rid of the 'default' site in multisite?
I have a multisite (sub directory style), and am wondering if i can delete the default site (sites/default)? I just want to get a 404 if the site doesn't exist, no fallback.

# Answer
You can leave the default directory in place. Just make sure there is no **settings.php** file in the default directory, and only the **sites/www.yoursite.com directories** will be accessed.

When you upgrade core, the default directory will always be replaced and will receive a new copy of default.settings.php, so it makes no sense to delete it.
> 2 votes

---
Tags: multi-sites
---


# Question
Title: Open Layers Views - Separate Data on Page and Block
I have a typical OpenLayers Locator proximity search on Drupal 7. I can search a map for my locations and that works great.

I also have a Product content type that is referenced to my locations. What I'd like to do is to display a table of products on my page AND a map of their corresponding locations.

How can I display two separate data sources on a single page?

# Answer
I just added a relationship to the Products entity in the view and then added the Product fields in the View. I then excluded most of the location data. This gave me a Products page with a map of locations!
> 0 votes

---
Tags: views, entities, javascript
---


# Question
Title: Check Login and display login page in views
I created a Search on my website with views exposed filters. I want only the logged in users to view the entire content. So, when the user clicks on View More.. Link I want them to be redirected to the log in page or pop up a login block.

Thanks, Prerna

# Answer
> 1 votes
In your view set the Access of the page display to role \> authenticated user. This will present an Access Denied message to anonymous users.

You can then enable the Login Toboggan module and enable "Present login for on access denied (403)". After the user logs in, they will be taken back to the view page automatically.

# Answer
> 0 votes
In your view's page display add PHP header like this:

```
<?php
  if (user_is_anonymous())
    drupal_goto('user/login');
?>

```

# Answer
> 0 votes
The simplest way I can think of is to use an access control module like Content Access. In Content Access you can set the permissions for accessing a node on a node by node basis, it is very flexible. You can set it up so that the content type you are using is viewable by authenticated users only by default.

Then you can use @rocketeerbkw recommendation of LobinToboggan to automatically show the user login form on 403 pages.

Your view will then link to the actual page that you want users to get to, but they won't be able to access it until they log in on that page.

---
Tags: views, users
---


# Question
Title: Possible permissions error with drush make
I am trying to run drush make distro.make but getting the following error. The only thing I can see I did different was ran sudo drush make distro.make once. Any ideas?

> copy(/http---updates.drupal.org-release-history-drupal-7.x): failed to open stream: Permission denied drush.inc:840 \[warning\]
>
> Could not download project status information from http://updates.drupal.org/release-history/drupal/7.x \[error\]
>
> Non-existent project type on project drupal

previously I was running without sudo and it was working fine.

# Answer
Problem was that running sudo drush had probably added some unwanted permissions to the cache folder. Deleting the folder solved the problem.
> 4 votes

---
Tags: drush
---


title: Use calendar.module in my custom module

text:
# Question
Title: Use calendar.module in my custom module
I am creating a module with 2 tabs, a short term calendar and a long term calendar. I made the tabs, but I'm already stuck..

How can I implement calendar.module to show a calendar on each tab?

This is the code of my tab:

```
  $items['planning/longterm'] = array(
    'title' => 'Long Term',
    'access callback' => TRUE,
    'page callback' => 'planning_page_longterm',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

```

In my callback function I try to call the calendar.module via this piece of code:

```
  if (module_exists('calendar')) {
    print theme('calendar_date_default_argument_alter', array('#item' => array('year' => '2013')));
  }

```

# Answer
> 0 votes
I would second the comment on trying out Views. You should be able to achieve what you want with the menu tabs and a specific calendar on that page with Views. Maybe try checking out the documentation. Without more detail in your question it is hard to say, but I'm pretty sure you don't need to make a custom module to do what you have written so far.

Also you probably should also specify which version of Drupal you are using. I'm assuming 7 but it is always better to let people know.

---
Tags: datetime
---


# Question
Title: How can I use PHP to print a view in the content area of a page?
The Private Message module displays conversations between users as "threads" that resemble e-mail or forum friends. I am attempting to customize the default display by printing a view that shows the recipient/sender profile information.

Through trial and error I arrived at the following code, which prints out the view content pane that I want.

```
  foreach($thread['participants'] as $participants => $participant ) {
    global $user;
    if ($user->uid !== $participant->uid) {
      print views_embed_view('profile_show_user_interests','show_interests_own', $participant->uid);
    }
  }

```

This code resides in privatemsg.pages.inc in `function privatemsg_view($thread)`, which returns the content of the page for rendering.

The problem with this is that `print views_embed_view()` prints the content pane out at the top of the page, above the header, with no extra markup. How can I print the content pane in the content region of the page?

# Answer
As a starting point I would have the function return the view rather than attempting to print it. Try:

```
 $content['view'][] = views_embed_view('profile_show_user_interests','show_interests_own', $participant->uid);

```

and then render it in the page at the proper place. (views\_get\_view might be better in this context.)
> 1 votes

---
Tags: views
---


# Question
Title: Created flag for "add friend", set a View, works but there's a problem
Ok, so now when a user looks at HIS profile, he gets the links to HIS list of friends, great! However, when the same user looks at someone else's profile, he sees the links and they point to THAT user's friends - and I don't want that...

I'd like the 'friends' link to only appear if I'm seeing my own profile page; when looking at someone else's profile I shouldn't be able to see THEIR list of friends.

# Answer
> 0 votes
It sounds like your view is already set up with the proper **Flagged: Node** relationship and "**User ID from URL**" contextual filter. If you edit the view and then edit the Flagged: Node relationship, you can try checking the box for "**Only display if flagged by the currently logged-in user**" and see if that helps you.

Keep in mind, this method will still display people that were flagged by both Person 1 and Person 2 (common friends, in other words). Another solution would be to have a private profile page and a public profile page, with different views on each; you might want to look into the **Profile2** module.

---
Tags: views, users, flags
---


# Question
Title: Filter User in Views based on taxonomy contextual filter?
I have some users with taxonomy term reference fields. Lets say users can be associated with regions.

When i view the user page i want to see all other users from the same region as the user i am looking at.

I created a views block on users with a contextual filter based on that taxonomy, but i cant get it to work ? Do i need some relationship ??

My Settings for the contextual filter:

* filter on User: Region (field\_region) / that is the taxonomy term reference field in the user
* provide default value -\> user ID from URL
* specify validatiion criteria -\> taxonomy term -\> vocabularies "Region" , filter value type -\> term name converted to term id

# Answer
> 2 votes
You are on the right track, but the contextual filter has to be changed. The user ID is not the region. If you wish to filter on the Region, you must first determine the Region for the user page you are on.

Switch the Provide default value to PHP Code. Then enter something like:

```
$user = menu_get_object('user');
return $user->field_region['und'][0]['taxonomy_term'];

```

This will load the term object for the region of the current user, and the filter can then limit the user list based on that term.

To eliminate the current user from this list, set upa second contextual filter in User:UID and set default value to Use ID from URL. Then open up the 'More' settings and check exclude.

# Answer
> 0 votes
With the help of Triskelion i succeeded. My Steps to adjust the filter:

* Add Relationship to the taxonomy reference in user. in my case User:Region and require this relationship
* Add a contextual filter on taxonomy term:name provide default value -\> php code : `$user = menu_get_object('user');return $user->field_region['und'][0]['taxonomy_term']->name;`
* Add second contextual filter on uid and provide default value user id from url. under more set to exclude the user from its page

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


title: Google analytics per page

text:
# Question
Title: Google analytics per page
I'd like to post alot of Google Analytics info about a page(node) on the page itself(visits, new visits, bounce rate, maybe even time series). What's the best module for this?

In particular, the info is for users that create their own pages and need to see analytics for their pages.

Any hints?

Thanks.

# Answer
Try Drupal SEO may be what you are looking for. http://drupal.org/project/seotools

From its project page:

> The Drupal SEO Tools module seamlessly integrates a sophisticated all-in-one suite of search engine reporting, analysis and optimization tools into your website. It provides a dashboard that integrates analytics reports with links to webmaster tools and vital Drupal SEO modules.

Hope that helps.
> 0 votes

# Answer
http://drupal.org/project/google\_analytics\_reports also provides this functionality. The 3.x branch includes Views support that allows you to create custom reports.

Some details from the project page:

> Google Analytics Reports module provides graphical reporting of your site's tracking data. Graphical reports include small path-based report in blocks, and a full path-based report.
> 0 votes

---
Tags: google-analytics
---


title: Patch a module loaded by a distribution

text:
# Question
Title: Patch a module loaded by a distribution
I am trying to make an installation profile that inherits the commerce kickstart distribution. In order to get this to work, I need to apply a bunch of patches through drush make.

First I have to apply a drupal core patch: http://drupal.org/node/1356276#comment-6654100

However the libraries module also needs to be made aware of the parent installation profile. So it needs to be patched as well.

My make file looks like this:

```
api = 2
core = 7.x

projects[drupal][type] = core
projects[drupal][patch][] = http://drupal.org/files/1356276-base-profile-d7-38-do-not-test.patch

projects[commerce_kickstart][type] = profile
projects[libraries][patch] =  patches/libraries-from-inherited-profiles.patch

```

The problem is that with this makefile drush will download the libraries module again to `sites/all/modules` and patch it there instead of just patching it in its original download location at `profiles/commerce_kickstart/modules/contrib/libraries`, thus I end up with the libraries module existing twice within one drupal installation.

The patch file for the libraries module looks like this:

```
diff --git a/libraries.module b/libraries.module
old mode 100644
new mode 100755
index 687fa29..bcf8824
--- a/libraries.module
+++ b/libraries.module
@@ -66,7 +66,6 @@
  */
 function libraries_get_libraries() {
   $searchdir = array();
-  $profile = drupal_get_path('profile', drupal_get_profile());
   $config = conf_path();

   // Similar to 'modules' and 'themes' directories in the root directory,
@@ -77,7 +76,8 @@
   // Similar to 'modules' and 'themes' directories inside an installation
   // profile, installation profiles may want to place libraries into a
   // 'libraries' directory.
-  $searchdir[] = "$profile/libraries";
+  foreach (drupal_get_profiles(drupal_get_profile()) as $profile)
+   $searchdir[] =  drupal_get_path('profile', $profile) . '/libraries';

   // Always search sites/all/libraries.
   $searchdir[] = 'sites/all/libraries';

```

How do I tell drush to simply patch libraries within the commerce kickstart directory and not download it again into `sites/all`?

# Answer
For now I have solved this by patching the make file of the commerce kickstart profile:

```
projects[commerce_kickstart][type] = profile

projects[commerce_kickstart][patch][] = patches/commerce_kickstart.patch

```

The content of `patches/commerce_kickstart.patch` is this:

```
diff --git a/drupal-org.make b/drupal-org.make
index bde036e..787f6ea 100755
--- a/drupal-org.make
+++ b/drupal-org.make
@@ -31,6 +31,7 @@
 projects[taxonomy_menu][subdir] = "contrib"
 projects[libraries][version] = 2.1
 projects[libraries][subdir] = "contrib"
+projects[libraries][patch][] = patches/libraries-from-inherited-profiles.patch
 projects[views_megarow][version] = 1.0
 projects[views_megarow][subdir] = "contrib"

```

The patch happes to be applied on the commerce kickstart before its own makefile is executed. When it finally get executed it will also applied my libraries module patch within its directory structure.
> 4 votes

---
Tags: 7, distributions, drush, version-control
---


title: Will Lime the future test suite?

text:
# Question
Title: Will Lime the future test suite?
Now that Drupal 8 is going to be based mostly on Symfony, is the TDD / unit testing going to change too?

For Symfony, Lime is the preferred testing suite. Is that true for Drupal 8 too?

# Answer
You linked the Symfony 1 documentation, which shows this warning.

> This version of Symfony is not maintained anymore. If some of your projects still use this version, consider upgrading.

The relevant link is the Testing chapter in the Symfony 2 book. Both Symfony 2 and Drupal 8 is using PHPunit although Drupal 8 didn't throw out the massive amount of functional tests written with our bastardized version of Simpletest. You can clone Drupal and in the `core` directory just run `phpunit` (if you have installed it already). Alternatively, enable the Testing module and then you can run the PHPunit tests from that UI.
> 5 votes

# Answer
Not sure about Lime, but Drupal 8 is set to use PHPUnit. See Deploy a PHPUnit system with a bottom-up approach.

> # Deploy a PHPUnit system with a bottom-up approach
>
> ## Issue Summary
>
> Replace the SimpleTest framework with PHPUnit.
>
> ## Problem/Motivations
>
> The SimpleTest framework no longer has the same level of maintenance than the PHP Unit framework. PHPUnit has become the standard; most frameworks use it (ZF1 & 2, Cake, Symfony2, ...) and is actively maintained, sable and works great for every codebase, scenario.
>
> Replacing the testing framework with PHPUnit will allow better consistency in the drupal 8 codebase, by aligning ourselves with Symfony2 testing tools. Moreover, it integrates better with IDE (NetBeans, Eclipse, IntelliJ IDEA), Continuous Integration servers such as Jenkins/Hudson, and with Sonar for static code analysis as well. It has also code coverage which is a huge +.

**EDIT**

Following the comment from chx below about me posting the wrong issue, I'm pretty sure that this is the issue that noted the progress of PHPUnit: Start using PHPUnit for unit tests
> 5 votes

---
Tags: 8, testing
---


# Question
Title: "The value in Date is not a valid date" error
I am editing an existing node of content type event, and am trying to update the Date using the date pop up. However, no matter what date I select I get the The value in

> "Date is not a valid date"

error.

The same issue appears when I try and add a new node with the same content type...

Any suggestions?

# Answer
> 1 votes
The latest dev version of clientside validation contains a fix to support more formats, so you can give it a try

# Answer
> 0 votes
I found that this error is definitely tied directly to the date popup widget. As a quick fix try changing your fields' widget type to **select list**.

# Answer
> 0 votes
This is a known issue tied to the date string formats you defined. As in the issue, changing the 'short' format definition from **dd.mm.YYYY** to the php date() string format of **d.m.Y** appears to have corrected the problem.

# Answer
> 0 votes
If you have installed Clientside Validation module disable it.

---
Tags: datetime
---


# Question
Title: How to add an external image to node with a module?
I have created a form through my module in which the user(anonymous) can enter an image URL and some title for the image. The link needs to be, like with remote stream wrapper, shown as an actual image. So this means, the image should be used from an external sources and not be download on my local server.

```
$node = new stdClass(); // Create a new node object
$node->type = "article"; // Or page, or whatever content type you like
node_object_prepare($node);

$node->title    = filter_xss($_GET['title']);
$node->language = en; // Or e.g. 'en' if locale is enabled

$file_path = $_GET['link'];

$file = (object) array(
        'uid' => 1,
        'uri' => $file_path,
        'filemime' => file_get_mimetype($file_path),
        'status' => 1,
);

$node->field_image[$node->language][0] = (array)$file;

$node->uid = 1; // UID of the author of the node; or use $node->name

node_save($node);

```

I have this code and it doesn't save the image URL. I'm sending the 'link' and 'title' properties through AJAX.

# Answer
> 1 votes
File field references are made on the `fid` column in the file\_managed table - you haven't saved the file object so it doesn't have a `fid`, and thus nothing to relate the field data to.

Just add a call to `file_save` after you've prepared the file object, but before you add it to the field on the node object:

```
file_save($file);

```

---
Tags: nodes, media, uri
---


# Question
Title: Using Ajax, how can I populate a div with Database Content from a form select?
This is what I have so far. I can populate the select field just fine, however when another option is selected I can not get the data to populate in the ajax callback div.

```
function product_comparison_menu(){
  $items = array();
  $items['design_product_comparison'] = array(
    'title'            => t('Product Comparison'),
    'menu_name' => 'menu-main-menu',
    'page callback'    => 'drupal_get_form',
    'access arguments' => array('access content'),
    'page arguments' => array('product_comparison_form'),
  );

  return $items;
}

/*
* Display output
*/
function product_comparison_form($form, &$form_state) {

  //Query DB for Rows
$query = db_select('product_comparison');
$query->fields('product_comparison', array('id', 'OtherCombo',));
$query->condition('DropdownCategory', 'Exit Devices');
$query->orderBy('OtherCombo', 'ASC');
$results = $query->execute();

    //define rows
$options = array();
foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
}

$form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
);

$form['results'] = array(
  '#type' => 'markup',
  '#prefix' => '<div id="product_comparison_ajax_wrapper">',
  '#suffix' => '</div>',
 );

 // If the form has been submitted, build up your results and display them
 if (isset($form_state['Exit Devices']['OtherCombo'])) {
   $row = db_select('product_comparison')
     ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
 ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

   $header = array();

   $form['results']['#markup'] = theme('table', array('header' => $header,'rows' => $rows));
  }
  else {
    $form['results']['#markup'] = '<p>The results will appear here when you change the dropdown option.</p>';
  }

 return $form;
}

function product_comparison_form_ajax($form, $form_state) {
  return $form['results'];
}

```

# Answer
> 3 votes
You need to populate data in the ajax callback `product_comparison_form_ajax` and then return `$form['results']`.

Your code should be as the following:

**Product comparison form**

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

  //Query DB for Rows
  $query = db_select('product_comparison');
  $query->fields('product_comparison', array('id', 'OtherCombo',));
  $query->condition('DropdownCategory', 'Exit Devices');
  $query->orderBy('OtherCombo', 'ASC');
  $results = $query->execute();

  //define rows
  $options = array();
  foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
  }

  $form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
  );

  // removed result condition

  $form['results'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="product_comparison_ajax_wrapper">',
    '#suffix' => '</div>',
    '#markup' => '<p>The results will appear here when you change the dropdown option.</p>',
  );

  return $form;
}

```

**Product comparison ajax callback**

```
function product_comparison_form_ajax(&$form, &$form_state) {
  if (isset($form_state['Exit Devices']['OtherCombo'])) {
    $row = db_select('product_comparison')
      ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
      ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

    $header = array(
      array('data' => 'Design Hardware'),
      array('data' => 'Design Img'),
      array('data' => 'Design URL'),
    );

    $rows = array();
    foreach ($result as $row) {
      $rows[] = array('data' => (array) $row);
    }

    // assign result to markup
    $form['results']['#markup'] = theme('table',array('header' => $header, 'rows' => $rows));

  }

  return $form['results'];
}

```

# Answer
> 0 votes
3 things to commment:

1. The variable `$row` is not the same the variable `$rows` that you pass in the theme function. I think it's a misspelling error.
2. Your `$header` variable is empty when you pass to theme table. I am not sure if it's necessary to send it with data.
3. To verify the table is empty, i've added a new variable called `empty` to your theme variables. The documentation fo theme\_table() in theme.inc says:

> empty: The message to display in an extra row if table does not have any rows.

I've changed 2 things in the next piece of code:

```
// If the form has been submitted, build up your results and display them
if (isset($form_state['Exit Devices']['OtherCombo'])) {
  $rows = db_select('product_comparison')
  ->fields('product_comparison',
    array('DesignHardware','DesignImg','DesignURL'))
  ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
  ->execute();

  $header = array();

  $form['results']['#markup'] = theme('table',
   array('header' => $header,'rows'=> $rows, 'empty' => 'empty table'));
  }else{
  $form['results']['#markup'] = '<p>The results will appear here when you  change the dropdown option.</p>';

```

}

---
Tags: forms, ajax
---


# Question
Title: How to display my block on search results page only if nothing found?
I want to place a webform block to make user able to inform about their special queries if no search results appeared.

# Answer
> 1 votes
To expose a webform as a block, go to the webform, and under the *webform\>\>form settings* tabs go to the bottom, open up the Advanced settings, and check 'Available as block'.

Then go to **/admin/structure/block** find your block and click on 'Configure'. The url will have the form **/admin/structure/block/manage/MODULENAME/BLOCKID/configure** (MODULENAME will be 'webform', and the BLOCKID will have the form 'client-block-$nid' where $nid is the node ID of the form). Keep a record of these.

Then copy the core template from the DRUPALROOT/modules/search/search-results.tpl.php to your theme directory, and edit it to look something like:

```
<?php if ($search_results): ?>
  <h2><?php print t('Search results');?></h2>
  <ol class="search-results <?php print $module; ?>-results">
  <?php print $search_results; ?>
  </ol>
  <?php print $pager; ?>
<?php else : ?>
  <h2><?php print t('Your search yielded no results');?></h2>
  <?php
    $block = block_load('MODULENAME', 'BLOCKID');
    print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))))
 ?>
<?php endif; ?>

```

This will print your block instead of the search help if there are no search results.

Now, so your theme can use this new template, you have to make it aware. Edit the theme's *template.php* file and look for a function called **THEMENAME\_preprocess\_search\_result(&$vars)** If it exists, add the following code. If it does not exist, create it and add the following code:

```
THEMENAME_preprocess_search_results(&$vars) {

  // ..... Existing code

  $vars['template_files'][] = 'search-results-' . $vars['module'];
}

```

Hope this helps.

# Answer
> 0 votes
Download and install Views block area.

From the module's project page:

> This module exposes all available blocks as a views area. This way you can add any block inside a footer or header from your view.
>
> Blocks that are generated by views, can't be selected. These blocks can be inserted by views areas.

To add a block as an area:

```
Go to the view that needs a block inside an area
Click on add next to header, footer or no result behavior
Select Global: Block area
Select the block that you want

```

---
Tags: blocks, search
---


# Question
Title: Change the way a node is themed based on an argument added to a URL
I am currently trying to eliminate my need for the panels module from a site I am working on and don’t have a lot of PHP experience. How would I go about changing the way a node is displayed based on an argument added to a URL? (E.g. http://example.com/node/123/argument.) I already have the node type themed but I need to display the node in a different form based on the argument. Thanks in advanced for your help.

# Answer
Since I didn't want to use Views to solve this. I came up with this solution:

I discovered that a simple if statement combined with preg\_match, Drupal's check\_plain (for security) did the job nicely. Once the conditions were set up, you can then use theme\_hook\_suggestions to make a nice logical nomenclature for the tpl.php files. The following code is inserted into the template.php file for your theme:

```
    function THEME_preprocess_node(&$variables, $hook)
    if (preg_match('/\/ARGUMENT$/', check_plain(current_path()))){
$variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__ARGUMENT';
    }

```

To use this script, replace the words THEME (with your theme's machine name), ARGUMENT (with the word you wish to use as the argument.

This will then use node--type--ARGUMENT.tpl.php for theming any page whose URL ends in /ARGUMENT.
> 0 votes

# Answer
one solution is to use Views. Create views page, for path add node/%/argument, choose Content on Format Show and View mode you want. See Entity view mode module for ability to add more View modes per entity. Add one to Article named "Custom view" for example. Add next code in template.php (change THEME to your maschine theme name).

```
function THEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__' . $variables['view_mode'];
}

```

Then copy node.tpl.php to node--custom-view.tpl.php in current the dir - if your already add new view mode with name "Custom view" and edit node view template as you want.

To have node--Content-Type--View-Mode.tpl.php like node--article--custom-view.tpl.php the above code must be

```
function THEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__' . $variables['view_mode'];
}

```

**EDIT**:

Programmaticaly solution with code in custom module:

```
function HOOK_menu() {
   $items['node/%/argument'] = array(
    'page callback' => 'node_custom_view',
    'page arguments' => array(1, 2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function node_custom_view($arg1, $arg2) {
  $content = '';

  if (is_numeric($arg1) && $arg2 == 'argument') {
    $node = node_load($arg1, $vid = NULL, $reset = FALSE);
    $content = drupal_render(node_view($node, $view_mode = 'custom_view', $langcode = NULL));
  }

  return $content;
}

```

"custom\_view" is our custom display for node created by Entity view mode module, then we enable this for content type from Manage display
> 0 votes

# Answer
Use the ThemeKey module. Here is a quote about it (from the module's project page):

> ... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to move commerce kickstart database to other domain
How to move commerce kickstart database to another domain.

When i copied my files and database tables and edited the settings.php the site just redirects to install.php

# Answer
It is showing the install.php file because it doesn't recognize your settings.php file - you need to check that this is in the correct sites folder (ex. 'default') and has read permissions for your web user.
> 1 votes

---
Tags: commerce
---


# Question
Title: Need to insert a custom node edit link in the node template
I've removed the tabs 'view and edit' from the node content type display. I need to provide a custom link to edit the particular node based on user permissions. I've used node/%/edit in node tpl but it does'n't work. Can someone help me with the proper method to achieve this

# Answer
In your node.tpl.php you have access to current `node` object `$node` and you can get the node id. You can check permissions for current logged user with user\_access function

So you can do the next thing in your node.tpl.php

```
<?php
      if (user_access('your_permission_here')){
       //create link for current node edit
       echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
      }
?>

```
> 5 votes

# Answer
This did it for me without having to worry about user permissions(default drupal permissions apply)... pasted it in the tpl for getting the edit link.

```
<?php
if (node_access('update',$node)){
print l(t('Edit'),'node/'.$node->nid.'/edit' );
}
?>

```
> 3 votes

---
Tags: theming, nodes
---


# Question
Title: Remove Locale settings from Logintoboggan
I have Logintoboggan installed to handle login/registration.

Upon registering a new user it displays an option to set up Locale Settings - I would like to have this removed but cannot figure out how.

I have disabled the site-wide option for users to be able to change locale settings but it still appears at registration/authorisation.

# Answer
> 0 votes
I seem to have fixed the issue by myself (again). For some reason the site-wide locale settings didn't stick so I just disabled and re-enable Logintoboggan and it works fine now

---
Tags: users, i18n-l10n
---


title: adding multiple content to homepage

text:
# Question
Title: adding multiple content to homepage
I am very new to Drupal. I want to add multiple content to my homepage,very simple,like this structure,I need to add two contents ,Main Content 1 and Main Content 2. I am able to add Main content 1 easily, but how can i add the main content 2 below the main content 1?. Will I be able to do it from the admin panel or I will need to change the theme structure?

# Answer
> 1 votes
You can easily customize your theme depend upon your requirement

Open up your theme's .info file and you should see some regions like this:

regions\[featured\] = Featured

regions\[content\] = Content

regions\[sidebar\_first\] = Sidebar first

regions\[sidebar\_second\] = Sidebar second

to add a new region just type in a new one in that .info file. I'd be careful of replacing any though as there are several regions in D7 that are required.

Then you'll need to print out your new region in your page.tpl.php file which goes something like this now:

```
<?php if ($page['sidebar_first']): ?>
      <div id="sidebar-first" class="column sidebar"><div class="section">
        <?php print render($page['sidebar_first']); ?>
      </div></div> <!-- /.section, /#sidebar-first -->
    <?php endif; ?>

```

Don't forget to clear your cache or you won't see the new region. It really helps to poke around in some other D7 themes and see how they've done things also.

taken from this source http://drupal.org/node/1088718

# Answer
> 0 votes
Many ways are there to create like this.

1. Panels module is used to design your home page like this.
2. views module can create home page like this.
3. If you have good coding experience then you can define two region there and create two block for your content then use that block. You can use node\_level\_blocks to create node blocks.

---
Tags: theming, nodes
---


# Question
Title: Simple way to change messages after node creation
Before I would use Custom Submit Messages to customize each message but, seems to not work as we like with Drupal 7.

Is there any other simple way that will allow to alter the message text after creating content?

# Answer
You can do it through Rules

Create a new rule configuration and set the event to Node | After saving new content.

Add a condition, Node | Content is of type and set CONTENT TYPES to Article, as shown in the following screenshot:

Add an Action and select System | Show a message on the site

By using the Action, After saving new content, we're asking Rules to react on content creation. This means that the rule will fire every time a new content has been created in the system. By using Conditions, we can tell Rules to only fire the action if the created content type is Article (or any other content type). In the MESSAGE field, we've used REPLACEMENT PATTERNS to insert chunks of data from the objects available in our current rule configuration.
> 8 votes

---
Tags: 7, status-messages
---


title: Creating a page from custom form

text:
# Question
Title: Creating a page from custom form
I am designing a site for ship maintenance. For now I have 3 files: `.info`, `.install`, and `.module`.

In `.install` the table schema is automatically installed into the database. It has information like ID, shipname, officer name etc.

Now in `.module` I have created a form in which you input shipname, officer name, subject, etc.

My problem is this: When I input my data in the form, the data is stored into the table and I display it into to a table (`my_module_submissions`).

Besides that I want to have a page created every time a user inputs the form and that the page title is taken from the subject.

It's like when you create new content like a story, you input *title, content*, and some other data. Then when you click submit you are redirected to the newly created page.

Currently I have the form which data is stored into a table, and I get that information and show it into a table (using `db_select`). How can i create the above?

Filling the information

now when i input the data i get my inputed data showned in this link : content/repair\_of\_main\_fuse\_box\_wiring

So i have a PAGE where i can go to

---

Now my situation right now is this :

I have created the same thing in php as the first picture . But i can only show my data like this :

Now i have the data but i have no link for every specific row in a table. I dont have a page a can go to for that data.

# Answer
Is it a drupal 7?

If so, its easily to create new entity type. More information here.

Why you don't like to use nodes to store your data? Just create new node type with required fields and add permission to create nodes of this type to all users.

In both cases you can use views to represent data into table format.
> 2 votes

---
Tags: forms
---


# Question
Title: Limit menu items available as possible parents on node creation
As I create a node I want to assign i to a menu item parent. I know that I can limit it to what menu(s) are available on:

> /admin/structure/types/manage/my\_type

But it would narrow it down to "only some of the menu items". For instance if I have a menu like this:

> * Main menu
>     + Home (page)
>     + Service type A (page)
>     + Service type B (page)
>     + Service type C (page)
>     + About us (page)
>     + Contact us (page)

If I then have content type "Service", I don't want the editor to by mistake place the new node under About us. They should only be able to select "Service type A" (or B or C).

I would be nice if I just missed the module that does this trick.

# Answer
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Creating Sign Up form for 2 types users in Drupal 7
I want to create a single user registration/ sign up form for two types of users e.g buyer and seller. When trying to register, a potential user will have the option of selecting between being a buyer or seller. After completing the form and clicking the sign up button, the user who chooses buyer is immediately logged in while the seller is taken to a page where he needs to provide additional information to complete his/her registration. I have downloaded and installed profile 2 and auto assign role but am not sure am on the correct path.

Thanks in anticipation.

# Answer
Sounds like a way to go. Additionally you may use the Rules module to redirect the seller to the profile page and the LoginToboggan module to login users immediately after registration. Also some Spam bot prevention may be useful. Generally I consider registration without user approval (by email) as harmful: A user can easily register himself in the name of another person. Drupals double opt-in usually helps to prevent that. LoginToboggan can delete users which did not approve their registration after x days.

Anyway here is a potentially cooking list:

* Add two roles: Buyer and Seller.
* Use the Auto Assign Role module to let the user choose between Buyer and Seller at registration time.
* Use the LoginToboggan module to login the user immediately after registration.
* Create a profile for Sellers using the Profile 2 module. Use Drupal permissions to make it accessible by Sellers only.
* Use the Rules module to redirect Sellers to their profile page if they have no profile yet.
* Optionally use the CAPTCHA module to prevent spam bot registrations.
> 2 votes

# Answer
You can probably add a Field to the User Accounts for `type_of_user` and have it be a select box with your 2 options. Require it at registration. Use Rules to say if Registration is submitted with Seller value set -- redirect to another page with other profile fields. If needed you can probably use Display Suite to limit the number of fields shown in the 2nd page for Buyer type users.

Another options is to simply use `hook_form_alter` in place of Rules for the above.
> 1 votes

---
Tags: users
---


# Question
Title: Running drush sql-sync between linux drupal alias as source and windows drupal alias as target throws rsync:chgrp error
i can see from this post that rsync is trying to set group on the file which may not make sense for windows. The question is, how can i pass rsync options while running the sql-sync command as

```
drush sql-sync @linux_alias @windows_alias

```

I can run the same command between two linux drupal aliases without any problems.

Thanks!

# Answer
> 0 votes
Okay, i got it running. Followed instructions at this blog and i'm able to run it.

Specifically:

> The best way to solve this, is simply to add the following to your alias definition file for your local site:

```
  'target-command-specific' => array (  //commands used when this alias is the target
'sql-sync' => array (
  'create-db' => TRUE,  //create new database(merged databases can be trouble!)
  'mode' => 'rultvz',  // override sql-sync default $mode = '-akz' from rsync.core.inc
),

```

),

---
Tags: drush
---


# Question
Title: how do I change the url based on a theme?
On some occasions, I've seen Drupal able to detect things like language and rewrite the url accordingly, so your actual displayed url reflects the detected value (like from http://www.mysite.com/foo/bar to http://www.mysite.com/en/foo/bar)

I want to do that based on the $theme\_key. I want all the data, when displayed in the 'fancytheme' theme, rewritten from http://www.mysite.com/foo/bar to http://fancytheme.mysite.com/foo/bar

* is that possible ?
* how would i go about ?
* is there a module out there that already does that ?

# Answer
Normally, you could accomplish this with URL rewrite rules or theme switching modules like ThemeKey but you're moving to a different sub-domain which Drupal is going to assume is a new database. The best way to do this then is to use the Domain Access module to simulate the use of a sub-domain without switching your database.

Domain Access is a little trickier to setup (read the install file carefully) but it allows separate themes for each subdomain with the "Domain Theme" module.

> Domain Theme -- Allows separate themes, theme settings and colors for each subdomain.
> 0 votes

---
Tags: 7, theming, uri
---


# Question
Title: How to determine the source (views/modules/blocks, etc) of content in different URLs?
I am working on re-designing an existing site for which I need to edit the output of each page (i.e. each URL). Is there a good way to determine where the data is coming from? By "where" I mean, is it a 'View'? or from a module? or combination of blocks?

I have tried devel & theme developer but that only tells me which tpl.php file but not the actual source.

# Answer
If you are comfortable looking through your database directly, the quickest way to find out where `$content` is coming from is to look at the `menu_router` table and reference the `path` and `page_callback` fields. For example, path `node` is generated (normally) by `node_page_default` and it creates the default front page. Looking through this table you can see where all the other paths on your system are referenced.

As for where all the other content comes from, eg, all the blocks in other regions of the page, there you have to look around through the `blocks` table and look at the various information there, eg, `module` and `delta` say which module creates the block and which one it is, `region` says where on the page it will be put, and `pages` have any restrictions as to what pages the core block module knows about.
> 0 votes

---
Tags: 7, uri
---


# Question
Title: boost module - no file to Disallow: /boost_stats.php
I have followed the installation guidelines and installed Boost, but where it states to add a line 'Disallow: /boost\_stats.php' for robots.txt doesnt seem to make sense as I dont have a boost\_stats.php file in root for search engines not to follow anyway. Do I really need to add this line?

# Answer
This file was a part of the Boost module in Drupal 6. It is no longer present in the Drupal 7 version. If you are using D7 this instruction can be ignored.
> 2 votes

---
Tags: 7, caching
---


# Question
Title: How do I update a node via a custom form?
I have built a custom form (in a module) that creates several related nodes in the database when submitted. Now, I need to create a module so that a user can update his/her submitted form data at a later date. Here's my rough plan:

(1) Determine the nodes that the user wants to update via a wildcard in a requested url; (2) retrieve the required data from the database; (3) build a form and insert the retrieved database values via the #value property; (4) bulid a submit function that uses db\_update to update the node

Is this the right approach for updating a node via a custom form? Here's my (not working) module code so far:

```
// Implements hook_menu().
function update_card_menu() {
    $items['update-card/%update_card'] = array(
        'page callback' => 'update_card_form',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

// Database query function.
function update_card_load($nid) {
    $query = db_select('node', 'n');
    $query -> condition('nid', $nid);
    $query -> join('card_number', 'cn', 'n.nid = cn.entity_id');
    $nodes = $query
    -> fields('n', array('nid', 'title'))
    -> fields('cn', array('field_card_name_nid'))
    // This query will get more complex - I need more nodes and more fields
    -> execute();
    foreach ($nodes as $field) {
        $card['nid'] = $field -> nid;
        $card['card number'] = $field -> field_card_number_nid;
    }
    return $card;
}

```

$card now contains some values I want to populate my update form:

Array ( \[nid\] =\> 123 \[card number\] =\> 456 )

But how do I get $card into my form builder function, so that I can populate my #value properties from this array? My code does not work.

```
/**
 * Renderable form array return function.
 */
function update_card_form() {
    return drupal_render(drupal_get_form('update_card_capture'));
}

/**
 * Form builder function.
 */
function update_card_capture($form, &$form_state, $card) {
    $form['nid'] = array(
        '#title' => t('nid'),
        '#type' => 'textfield',
        '#value' => $card->nid
    );
        $form['card number'] = array(
        '#title' => t('Card number'),
        '#type' => 'textfield',
        '#value' => $card->card_number
    );
}

```

# Answer
You need to use hook\_menu() to register the path and callback function, like so:

```
<?php
function hook_menu() {
  $items['some-path/%node'] = array( // %node will use the node_load() function that's already provided by node.module.
    'type' => MENU_CALLBACK // This is just a callback item, it will not appear in any "menus"
    'page callback' => 'drupal_get_form'
    'page arguments' => array('the_form_function_name', 1) // Where 1 = the %node wildcard
    'access callback' => 'node_access',
    'access arguments' => array('update', 1), // The user must be able to update the node
  );
  return $items;
}
?>

```

Then build a simple form that provides fields to alter on the node, and run `node_save()` in the submit handler to save any modifications you make to the node.

```
<?php
function the_form_function_name($form, &$form_state, $node) {
  drupal_set_title('Now editing node ' . check_plain($node->title));

  // Just store the entire $node object in a custom form property. Easy.
  $form['#node'] = $node;

  // An example form field that we'll use to update the node's title.
  $form['new_title'] = array(
    '#title' => 'Title',
    '#type' => 'textfield',
    '#default_value' => $node->title,
  );

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

  return $form;
}

function the_form_function_name_submit(&$form, &$form_state) {
  $form['#node']->title = $form_state['values']['new_title'];
  // Save the modified node object (http://api.drupal.org/node_save)
  if (node_save($form['#node'])) {
    drupal_set_message('Updated the node.');
  } else {
    drupal_set_message('Could not update the node.', 'error');
  }
}
?>

```

This is just sample code – I have not tested, but it should work barring any typos.

You would hit this via: http://example.com/some-path/123 where 123 is the node ID of the node you want to edit.
> 3 votes

# Answer
Solution for point 1: Implement hook\_menu()

The code should be something like this:

```
$items['my-view/%'] = array(
  'page callback' => 'mymodule_create_form', // Function name that create the form
  'page arguments' => array(1), // You pass the wildcard(%) value, in this case, the id of the node that you will use to load with node load()
)

```

Point 2 : Always node\_load(). It will give you the chance to act with hooks and you will can add or delete fields without touch the querys.

Point 3: I would reuse the form that you\`ve created when a node is added. You will have to fill the fields in form using #value property.

Point 4: node\_save(). Updated the node object that you loaded in point 2.
> 0 votes

---
Tags: forms
---


# Question
Title: How do I run unit tests against datasets? (DrupalWebTestCase and DrupalTestCase)
I am testing a module that I am writing against the Unit Testing framework that comes with Drupal 7. All makes sense, and everything asserts as it should.

My question though, is it possible to run test cases against test data?

I can think of a few options/answers:

* Trick the unit test into not setting up a test database, and just run against the live data (I don't want to do this, its hackish)
* It's also very possible that testing against test data is not the place of a unit test, because technically a unit test should pass if there is data or not - from my understand of unit testing.

Should functionality testing be done in a different place than the SimpleTest framework? Or is there a way to test against data sets?

# Answer
Drupal 8 contains tests for verifying an upgrade from Drupal 7 would be executed correctly. Those tests basically create Drupal 7 tables, fill them with the required values, and call update.php.

You could need to create a upgrade/update test for your module, or you could test how a function behaves when it reads data from the database that are not in the format it expects.
In the first case, you would need to override the `setUp()` method, and avoid calling `parent::setUp()`; in the second case, you would fill the database table used from the test with the test data, call the function, and check what the return value is.

Apart from testing an update, I can think only of a case where a test would need to fill a database table, since:

* If the table contains what entered from users, then the test should verify the form validation handler correctly shows error for wrong input
* If the table contains data entered from another module, that module should be using a function your module implements, and the test should just check what the function does when it receives wrong/unexpected values

It could be your module is using data from a table that is created from another module, which is not exposing an API to load/save data in that table. In that case, if you know there is another module that enters *unexpected data*, you could need to verify your module is able to handle that data.
> 1 votes

---
Tags: 7, testing
---


# Question
Title: Send Notification to users with username and password
I have imported a set of user information into drupal website and all the users are active.

Now I need to generate the password for each user and send an email to them to notify them that the account has been created.

I found the code here which shows how to update the password of the user by code.

```
$account = user_load(array('uid' => $userdata['uid']));
$password = user_password();
$username = $userdata['username'];
$updates = array(
  'pass' => $password,
   'roles' => array(
    <rid> => '<role title>';
 ),
);

user_save($account, $updates);

```

Now how can I notify the users of their new username and password.

# Answer
You can notify your user by mail using drupal\_mail either at the time of updating your password. You arrange your username/password in some template using HTML & send that by help of the above given function drupal\_mail. I hope this help. Let me know if do..
> 2 votes

# Answer
Drupal will automatically send out a user with a one time link to set the password when you toggle an account's status from "Blocked" to "Active" (at least this happens when you've set up acoounts so that admin approval is required to create an account - I haven't tested other configurations). This is IMHO better than generating passwords and sending them in cleartext. It also have the advantage of requiring zero PHP programming on your part.

If you want to send out passwords in clear text, the Registration Password Token module provides a token \[user:password\]. Since the site administrator allowed to customize the text of the e-mail that is sent to the user after registration have completed, you can then edit the welcome email in the admin GUI to include this token. This solution also requires zero PHP programming on your part, but you must install an extra module.

Caveat: Sending passwords with unencrypted email is a security hazard. This is why Drupal does not provide this function out of the box (as noted by senior core developer webchick: http://drupal.org/node/660302#comment-2592510).
> 1 votes

---
Tags: users
---


# Question
Title: How to apply opacity to just a portion of the image?
I've got a slideshow on the homepage which consists of an image and with text in front of it, in the bottom half of the image. I would like to apply opacity to the lower part of the image. Is there a way to do this using css?

# Answer
> 0 votes
You need to use the image with an absolutely positioned div:

Check here for the demo

SO Answer

# Answer
> 0 votes
What I would have done is to add a new `div` or `span` element with the same background as the page, then absolute position it between the image and the text using `z-index`. How the CSS looks depends on your page layout and html structure, but note that all elements needs a `position` value for `z-index` to work.

---
Tags: theming
---


# Question
Title: User Login Destination | to his first submission | Webforms
i have a career form built with webforms ; I need the users to go back to their first submission when they come back to the site again .

Login Destinations | can help me with that . but it will send only to a specific URL . where in my case every user have its own submission and i want him to return back to it in Edit mode when he/she logins again .

any clues / thanks

# Answer
You can achieve using hook\_user\_login() function.

```
function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location.
  // Get the logic and fetch where do you want to redirect.
  // Here i am redirecting to node 34. You can fetch your own webform submission path
  // where do you want to redirect.
  // Fetch the submission of done by the current users. by using http://api.drupalize.me/api/drupal/function/webform_get_submissions/7 function
  $redirection = 'node/34';

// Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}

```
> 2 votes

---
Tags: webforms, users
---


# Question
Title: Want to show url like termname (parent)/[termname] (Child: referenced by node) /node (node which is referenced to particular term)
Having problem to show url like termname (parent)/\[termname\] (Child: referenced by node) /node (node which is referenced under particular term)

i want this http://www.example.com/pets/cats/diseases/4-normal-diseases-of-kittens

here **pets** is parent term name
cats is child of parent 'pets' term name
diseases again sub term name of 'cats'
'4-normal-diseases-of-kittens' is article term referenced to diseases

Thanks in advance

# Answer
In your URL aliases patterns, use this token : **\[node:YOURTAXONOMYFIELD:parents-all\]** (*Ancestors of the term, i.e. parent of all above hierarchy levels*).

Then your whole pattern for your node type will be \[node:YOURTAXONOMYFIELD:parents-all\]/\[node:title\].

If you have languages matters, I guess it might work with i18n prefix.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: Custom Apache Solr search per usertype (Profile2 Module)?
I have a site that enables you to register either as a "Care giver" or a "Patient". The patient has a different profile (Profile2 module) with options such as the type of care they need, the amount of money they can pay a care giver, etc.

The care giver profile has a work profile (much like a resume).

What I want to accomplish:

Create a custom "Search patients" search for the care givers Create a custom "Search care givers" search for the patients.

How do I limit apachesolr to a profile2 search?

# Answer
Checkout the Search API module \- this was developed to solve problems exactly like this. With Search API, you can configure multiple search engines, define the datasource it pulls them from (ex. Apache Solr) and then use its built-in views integration to create custom search sets (ex. for care givers pull only from these entities / content types, and show only these fields).
> 1 votes

# Answer
You can also create new custom search page via apachesolr module and provide view integration with Apache Solr Views module. However Search API solution is more flexible and has better integration with Panels, Views and other contrib modules.
> 0 votes

---
Tags: search, users
---


# Question
Title: Having my own theme for creating and editing Nodes: No WYSIWYG Editor
I disabled the option "Use the administration theme when editing or creating content" so I see everything in the default theme. But now I got a problem: The JS Drupal object is on the bottom of the page (like in a usual page all JS files should be on the bottom). But CKEditor (which I'm using) needs that object in head.

**//update:** I checked the scripts and found out, that ckeditor is executed on the very top of all scripts. The Drupal object on the other hand is on the bottom. I tried to reverse the array, but still the same result. Even jQuery is loaded after CKEditor.

**//update2:** Okay I changed the order by putting weight on the CKEditor script files and set the scope of every script file to footer, but still the Drupal object is under all files, no matter what weight I give $js\['settings'\]. Maybe that's the wrong item?

Thanks

# Answer
Since the weight did not work as expected I tried to set the scope for every script to 'header' except for ckeditor files. \> **Did not work**

Because I had no clue I tried the opposite way:

```
  // Set scope for every script to footer.
  foreach ($js as $index => $value) {
    $js[$index]['scope'] = 'footer';
  }

  // Except for ckeditor files.
  $js_ckeditor_utils = &$js['sites/all/modules/ckeditor/includes/ckeditor.utils.js'];
  $js_ckeditor_utils['scope'] = 'header';
  $js_ckeditor = &$js['sites/all/libraries/ckeditor/ckeditor.js'];
  $js_ckeditor['scope'] = 'header';

```

**This works** \- I don't know why, but it works.
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How can I add keywords in my site without module?
I'm using Drupal 7 and want to add meta tags in my theme. How can i do it without any module?

# Answer
Using a module is the preferred way, as in that way you don't need to edit a theme, or create a sub-theme to set meta tags.
The alternative would be changing the html.tpl.php template used from the theme, and add a call to a function present in its template.php file that returns the meta tags to add to the page.

There is one case where editing the theme being used, or sub-theming it, to add the meta tags would make sense: when the meta tags are very specific for the theme being used that they should not added to every theme used from the site.

I would also prefer using a module as I would not need to worry about updating the module for a new Drupal version, or writing the update functions.
If, viceversa, I need to be 100% sure there will be a module version for the next Drupal, I would write my own custom module, knowing that it's just me that can fix any security issues I would introduce in the code (which also mean I am left alone with finding any security issue).
> 2 votes

---
Tags: 7, meta-tags
---


# Question
Title: How to make several instances of nivo slider in Drupal 7?
I develop a web site using the Drupal 7 cms. I use Nivo Slider and it works perfectly for me. I used nivo slider for the front page of the site. When I configured the nivo slider it's settings are displayed under structure in the Drupal CMS menu. Basically, I have to update images and set transitions and etc.

Now the problem is I have another page where I need to add a new slideshow. But I don't know how to make another instance of nivo slider and use it. Since this is a CMS I guess there should be a easy way to handle this.

I think my problem is clear. If not, please ask in comments where I have to clarify my problem.

# Answer
You might want to take a look at the Views Nivo Slider module. It allows you to construct the slider using views. Since you can create blocks with views, you should be able to build several galleries (by creating other views).
> 1 votes

---
Tags: javascript
---


title: JavaScript loading order

text:
# Question
Title: JavaScript loading order
I've installed eu-cookie-compliance module in few projects and everywhere it worked as expected but in one project I have problems with loading JavaScript in correct order. Even if I implement hook\_js\_alter and set higher weights, eu-compliance JavaScript is loaded before misc/drupal.js and misc/jquery.js. Is there any better way to reorder this JavaScript?

# Answer
You could always change the group it's in:

```
function MYMODULE_js_alter(&$js) {
  $js['path/to/eu-cookie-compliance.js']['group'] = JS_DEFAULT;
}

```

Drupal's misc JS, jQuery etc, should all be in `JS_SYSTEM`, which has a lower weighting than `JS_DEFAULT`. There's also `JS_THEME` which has a height weighting than `JS_DEFAULT`.

The `drupal_add_js()` docs discuss the whole JS weighting thing in much greater detail.
> 9 votes

---
Tags: 7, javascript
---


# Question
Title: How to find all Drupal modules which has dependence
I would like to know if it possible to find all contributed modules that depend, for example, on the Subform module.

This information could be useful if you are working with a module, and want to create yours because you don't know that the same module already exists.

# Answer
There is only way, and it is coping all the modules. Here is opinion of Lin Clark.
> 0 votes

# Answer
That's really easy to do with Gotta Download Them All. Once you have downloaded all the modules, you can just run a grep command to search the whole contribution space.
> 2 votes

---
Tags: version-control
---


title: Hide a field label

text:
# Question
Title: Hide a field label
Is there a way to hide the field label when rendering a custom field in Drupal 7?

In my node template I have:

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

```

Which gives me:

```
<div class="field field-name-field-image field-type-image field-label-above">
  <div class="field-label">Image: </div>
  <div class="field-items">
    <div class="field-item even">
      <img typeof="foaf:Image" src="http://site.com/sites/default/files/image.jpg" alt="">
    </div>
  </div>
</div>

```

I'd like to not have the `<div class="field-label">Image: </div>`.

Is there a way to get rid of this other than in the CSS or manually creating the markup?

I've tried `unset($content['field_image']['#title'])`, but that gives me `<div class="field-label">: </div>`.

# Answer
> 25 votes
Instead of hardcoding the setting for field labels in the template you should instead use the setting under `Manage display` tab where you add and remove fields for your entity.

# Answer
> 11 votes
To hide the name of a custom field (file field in this case with the name "file") in order to only show a list of downloadable files and not the name of the field do the following:

* Choose the Content Type that contains the file field (I created a new type called "File List")
* Navigate to the "Manage Fields" Tab
* Under Label choose "Hidden" and for Format, "Generic File"
* Save and create a new node of this content type and the name "file" should no longer be displayed

# Answer
> 9 votes
```
$content['field_image']['#label_display']='hidden';

```

# Answer
> 7 votes
Yes, using the #title\_display property of the Form API.

# Answer
> 4 votes
using the template `field.tpl.php` you can remove or customize the label (`$label` in the template) of your field. to use it you must add the template field `field.tpl.php` to your theme:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
    <?php endforeach; ?>
  </div>
</div>

```

---
Tags: 7, theming, entities
---