# Question
Title: Enable a node's menu item when on that node?
I have a node for which there is a menu item. I want this menu item to be disabled except when the user is viewing that node. Can I do this, and if so how?

# Answer
I will write a method that you can use by simply editing your theme's `template.php` file (without having to write your own module), and overriding

functions. YES, that's correct, unfortunately for the correct markup, you have to override all of the above mentioned functions in your own theme, to avoid rendering empty `<li>` elements in the default main menu, in the Superfish menu or the Site map module's own menu. I will assume you haven't already overridden them.
I tested it, so this code should be working, but please ask if you have any kind of questions.

1. First, please open your theme's `template.php` in a text editor of your choice.
2. Paste the whole code below into the opened `template.php`.

```
/**
 * Should this link be hidden?
 *
 * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
 *
 * @param string $link_path The path that should be inspected.
 * @return boolean
 */
function YOURTHEMENAME_link_should_be_hidden($link_path) {

    // in this example, I let "contact" and "node/9" links only be visible
    // on their own path (so for example, I let "contact" path be visible
    // in the menu if the user opened "example.com/contact").
    $your_paths_to_show_in_menu_only_on_their_own_path = array('contact', 'node/9'); // SUBSTITUTE IT with yours - empty cache every time you change that
    $is_link_to_hide = in_array($link_path, $your_paths_to_show_in_menu_only_on_their_own_path);
    if ($is_link_to_hide) {
        $is_current_page_self = ($link_path == $_GET['q']);
        // these links will be visible only on their own paths -
        // BUT here you can define other paths too where they can be visible at!
        // So for example, you want "example.com/node/9" to be visible when visiting its own path
        // AND when visiting "example.com/node/3" OR "example.com/any_other_path".
        // But if you do NOT want any other pages for these links to be visible at, then
        // just leave it empty (like this: array()).
        $link_also_visible_at_paths = array('node/3', 'any_other_path'); // SUBSTITUTE IT with your paths! - empty cache every time you change that
        $element_can_be_visible = $is_current_page_self || (!empty($link_also_visible_at_paths) && in_array($_GET['q'], $link_also_visible_at_paths));

        if (!$element_can_be_visible) {
            return TRUE;
        }
    }
    return FALSE;
}

/**
 * Overriding theme_menu_link()
 *
 * @see http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7
 */
function YOURTHEMENAME_menu_link(array $variables) {
    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($variables['element']['#href'])) {
        return '';
    }

    $element = $variables['element'];
    $sub_menu = '';

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

/**
 * Helper function that builds the nested lists of a Superfish menu.
 * @see theme_superfish_build()
 */
function YOURTHEMENAME_superfish_build($variables) {

    $output = array('content' => '');
    $id = $variables['id'];
    $menu = $variables['menu'];
    $depth = $variables['depth'];
    $trail = $variables['trail'];
    // Keep $sfsettings untouched as we need to pass it to the child menus.
    $settings = $sfsettings = $variables['sfsettings'];
    $megamenu = $settings['megamenu'];
    $total_children = $parent_children = $single_children = 0;
    $i = 1;

    // Reckon the total number of available menu items.
    foreach ($menu as $menu_item) {
        if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
            $total_children++;
        }
    }

    foreach ($menu as $menu_item) {

        $show_children = $megamenu_wrapper = $megamenu_column = $megamenu_content = FALSE;
        $item_class = $link_options = $link_class = array();
        $mlid = $menu_item['link']['mlid'];

        /**
         * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
         */
        if (YOURTHEMENAME_link_should_be_hidden($menu_item['link']['link_path'])) {
            continue;
        }

        if (!isset($menu_item['link']['hidden']) || $menu_item['link']['hidden'] == 0) {
            $item_class[] = ($trail && in_array($mlid, $trail)) ? 'active-trail' : '';

            // Add helper classes to the menu items and hyperlinks.
            $settings['firstlast'] = ($settings['dfirstlast'] == 1 && $total_children == 1) ? 0 : $settings['firstlast'];
            $item_class[] = ($settings['firstlast'] == 1) ? (($i == 1) ? 'first' : (($i == $total_children) ? 'last' : 'middle')) : '';
            $settings['zebra'] = ($settings['dzebra'] == 1 && $total_children == 1) ? 0 : $settings['zebra'];
            $item_class[] = ($settings['zebra'] == 1) ? (($i % 2) ? 'odd' : 'even') : '';
            $item_class[] = ($settings['itemcount'] == 1) ? 'sf-item-' . $i : '';
            $item_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
            $link_class[] = ($settings['itemdepth'] == 1) ? 'sf-depth-' . $menu_item['link']['depth'] : '';
            $item_class[] = ($settings['liclass']) ? $settings['liclass'] : '';
            if (strpos($settings['hlclass'], ' ')) {
                $l = explode(' ', $settings['hlclass']);
                foreach ($l as $c) {
                    $link_class[] = $c;
                }
            }
            else {
                $link_class[] = $settings['hlclass'];
            }
            $i++;

            // Add hyperlinks description (title) to their text.
            $show_linkdescription = ($settings['linkdescription'] == 1 && !empty($menu_item['link']['localized_options']['attributes']['title'])) ? TRUE : FALSE;
            if ($show_linkdescription) {
                if (!empty($settings['hldmenus'])) {
                    $show_linkdescription = (is_array($settings['hldmenus'])) ? ((in_array($mlid, $settings['hldmenus'])) ? TRUE : FALSE) : (($mlid == $settings['hldmenus']) ? TRUE : FALSE);
                }
                if (!empty($settings['hldexclude'])) {
                    $show_linkdescription = (is_array($settings['hldexclude'])) ? ((in_array($mlid, $settings['hldexclude'])) ? FALSE : $show_linkdescription) : (($settings['hldexclude'] == $mlid) ? FALSE : $show_linkdescription);
                }
                if ($show_linkdescription) {
                    $menu_item['link']['title'] .= '<span class="sf-description">';
                    $menu_item['link']['title'] .= (!empty($menu_item['link']['localized_options']['attributes']['title'])) ? $menu_item['link']['localized_options']['attributes']['title'] : array();
                    $menu_item['link']['title'] .= '</span>';
                    $link_options['html'] = TRUE;
                }
            }

            // Add custom HTML codes around the menu items.
            if ($sfsettings['wrapul'] && strpos($sfsettings['wrapul'], ',') !== FALSE) {
                $wul = explode(',', $sfsettings['wrapul']);
                // In case you just wanted to add something after the element.
                if (drupal_substr($sfsettings['wrapul'], 0) == ',') {
                    array_unshift($wul, '');
                }
            }
            else {
                $wul = array();
            }

            // Add custom HTML codes around the hyperlinks.
            if ($settings['wraphl'] && strpos($settings['wraphl'], ',') !== FALSE) {
                $whl = explode(',', $settings['wraphl']);
                // The same as above
                if (drupal_substr($settings['wraphl'], 0) == ',') {
                    array_unshift($whl, '');
                }
            }
            else {
                $whl = array();
            }

            // Add custom HTML codes around the hyperlinks text.
            if ($settings['wraphlt'] && strpos($settings['wraphlt'], ',') !== FALSE) {
                $whlt = explode(',', $settings['wraphlt']);
                // The same as above
                if (drupal_substr($settings['wraphlt'], 0) == ',') {
                    array_unshift($whlt, '');
                }
                $menu_item['link']['title'] = $whlt[0] . check_plain($menu_item['link']['title']) . $whlt[1];
                $link_options['html'] = TRUE;
            }

            if (!empty($menu_item['link']['has_children']) && !empty($menu_item['below']) && $depth != 0) {
                // Megamenu is still beta, there is a good chance much of this will be changed.
                if (!empty($settings['megamenu_exclude'])) {
                    if (is_array($settings['megamenu_exclude'])) {
                        $megamenu = (in_array($mlid, $settings['megamenu_exclude'])) ? 0 : $megamenu;
                    }
                    else {
                        $megamenu = ($settings['megamenu_exclude'] == $mlid) ? 0 : $megamenu;
                    }
                    // Send the result to the sub-menu.
                    $sfsettings['megamenu'] = $megamenu;
                }
                if ($megamenu == 1) {
                    $megamenu_wrapper = ($menu_item['link']['depth'] == $settings['megamenu_depth']) ? TRUE : FALSE;
                    $megamenu_column = ($menu_item['link']['depth'] == $settings['megamenu_depth'] + 1) ? TRUE : FALSE;
                    $megamenu_content = ($menu_item['link']['depth'] >= $settings['megamenu_depth'] && $menu_item['link']['depth'] <= $settings['megamenu_levels']) ? TRUE : FALSE;
                }
                // Render the sub-menu.
                $var = array(
                  'id' => $id,
                  'menu' => $menu_item['below'],
                  'depth' => $depth, 'trail' => $trail,
                  'sfsettings' => $sfsettings
                );
                $children = theme('superfish_build', $var);
                // Check to see whether it should be displayed.
                $show_children = (($menu_item['link']['depth'] <= $depth || $depth == -1) && $children['content']) ? TRUE : FALSE;
                if ($show_children) {
                    // Add item counter classes.
                    if ($settings['itemcounter']) {
                        $item_class[] = 'sf-total-children-' . $children['total_children'];
                        $item_class[] = 'sf-parent-children-' . $children['parent_children'];
                        $item_class[] = 'sf-single-children-' . $children['single_children'];
                    }
                    // More helper classes.
                    $item_class[] = ($megamenu_column) ? 'sf-megamenu-column' : '';
                    $item_class[] = $link_class[] = 'menuparent';
                }
                $parent_children++;
            }
            else {
                $item_class[] = 'sf-no-children';
                $single_children++;
            }

            $item_class = implode(' ', array_filter($item_class));

            if (isset($menu_item['link']['localized_options']['attributes']['class'])) {
                $link_class_current = $menu_item['link']['localized_options']['attributes']['class'];
                $link_class = array_merge($link_class_current, array_filter($link_class));
            }
            $menu_item['link']['localized_options']['attributes']['class'] = $link_class;

            $link_options['attributes'] = $menu_item['link']['localized_options']['attributes'];

            // Render the menu item.
            $output['content'] .= '<li id="menu-' . $mlid . '-' . $id . '"';
            $output['content'] .= ($item_class) ? ' class="' . trim($item_class) . '">' : '>';
            $output['content'] .= ($megamenu_column) ? '<div class="sf-megamenu-column">' : '';
            $output['content'] .= isset($whl[0]) ? $whl[0] : '';
            $output['content'] .= l($menu_item['link']['title'], $menu_item['link']['link_path'], $link_options);
            $output['content'] .= isset($whl[1]) ? $whl[1] : '';
            $output['content'] .= ($megamenu_wrapper) ? '<ul class="sf-megamenu"><li class="sf-megamenu-wrapper ' . $item_class . '">' : '';
            $output['content'] .= ($show_children) ? (isset($wul[0]) ? $wul[0] : '') : '';
            $output['content'] .= ($show_children) ? (($megamenu_content) ? '<ol>' : '<ul>') : '';
            $output['content'] .= ($show_children) ? $children['content'] : '';
            $output['content'] .= ($show_children) ? (($megamenu_content) ? '</ol>' : '</ul>') : '';
            $output['content'] .= ($show_children) ? (isset($wul[1]) ? $wul[1] : '') : '';
            $output['content'] .= ($megamenu_wrapper) ? '</li></ul>' : '';
            $output['content'] .= ($megamenu_column) ? '</div>' : '';
            $output['content'] .= '</li>';
        }
    }
    $output['total_children'] = $total_children;
    $output['parent_children'] = $parent_children;
    $output['single_children'] = $single_children;
    return $output;
}

/**
 * Overriding theme_site_map_menu_link()
 *
 * @param array $variables
 * @return string
 */
function YOURTHEMENAME_site_map_menu_link($variables) {

    $element = $variables['element'];
    $sub_menu = '';

    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($element['#href'])) {
        return '';
    }

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

/**
 * Returns HTML for a set of links.
 * @see theme_links()
 */
function YOURTHEMENAME_links($variables) {
    $links = $variables['links'];
    $attributes = $variables['attributes'];
    $heading = $variables['heading'];
    global $language_url;
    $output = '';

    if (count($links) > 0) {
        $output = '';

        // Treat the heading first if it is present to prepend it to the
        // list of links.
        if (!empty($heading)) {
            if (is_string($heading)) {
                // Prepare the array that will be used when the passed heading
                // is a string.
                $heading = array(
                  'text' => $heading,
                  // Set the default level of the heading.
                  'level' => 'h2',
                );
            }
            $output .= '<' . $heading['level'];
            if (!empty($heading['class'])) {
                $output .= drupal_attributes(array('class' => $heading['class']));
            }
            $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
        }

        $output .= '<ul' . drupal_attributes($attributes) . '>';

        $num_links = count($links);
        $i = 1;

        foreach ($links as $key => $link) {

            /**
             * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
             */
            if (YOURTHEMENAME_link_should_be_hidden($link['href'])) {
                continue;
            }

            $class = array($key);

            // Add first, last and active classes to the list of links to help out themers.
            if ($i == 1) {
                $class[] = 'first';
            }
            if ($i == $num_links) {
                $class[] = 'last';
            }
            if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
                && (empty($link['language']) || $link['language']->language == $language_url->language)) {
                $class[] = 'active';
            }
            $output .= '<li' . drupal_attributes(array('class' => $class)) . '>';

            if (isset($link['href'])) {
                // Pass in $link as $options, they share the same keys.
                $output .= l($link['title'], $link['href'], $link);
            }
            elseif (!empty($link['title'])) {
                // Some links are actually not links, but we wrap these in <span> for adding title and class attributes.
                if (empty($link['html'])) {
                    $link['title'] = check_plain($link['title']);
                }
                $span_attributes = '';
                if (isset($link['attributes'])) {
                    $span_attributes = drupal_attributes($link['attributes']);
                }
                $output .= '<span' . $span_attributes . '>' . $link['title'] . '</span>';
            }

            $i++;
            $output .= "</li>\n";
        }

        $output .= '</ul>';
    }

    return $output;
}

/**
 * Theming links (theme_link())
 * @see http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_link/7
 *
 */
function YOURTHEMENAME_link($variables) {
    /**
     * @see http://drupal.stackexchange.com/questions/27907/enable-a-nodes-menu-item-when-on-that-node/27922
     */
    if (YOURTHEMENAME_link_should_be_hidden($variables['path'])) {
        return '';
    }

    return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</a>';
}

```
3. Substitute `YOURTHEMENAME` with your own theme's name.
4. Substitute the values of `$your_paths_to_show_in_menu_only_on_their_own_path`and `$link_also_visible_at_paths` variables in the previous step with your appropriate values. In the previous example, I hide the `"contact"` AND `node/9` pages' menu link by default, and let them only be visible when we are viewing these pages themselves OR when displaying `node/3` or `any_other_path` paths (so in any other cases, I don't see the link to `"contact"` or `node/9`).
5. Save the file.
6. Clear the cache!

**So the final code should look similar to this: http://pastebin.com/PzQFhykn.**

**BUT in your exact case**, you would like to hide `node/425`, so your code should look like this: http://pastebin.com/DKi5aSyq

Ask if something isn't quite clear.
> 2 votes

---
Tags: 7, routes
---


title: How do I edit a block's default title?

text:
# Question
Title: How do I edit a block's default title?
"Powered by Drupal" is a footer block I need to change to my name for my website.

How do I edit its default title?

# Answer
> 1 votes
In drupal6, you can go into the block admin screen for that block and change the title there. If you are meaning the title/hover title for the drupal image itself, you can create a function in your theme's template.php file along the lines of:

```
function YOURTHEME_system_powered_by($image_path) {
  $image = theme('image', $image_path, t('Powered by Drupal, an open source content management system'), t('Powered by Drupal, an open source content management system'));
  return l($image, 'http://drupal.org', array('html' => TRUE, 'absolute' => TRUE, 'external' => TRUE));
}

```

and just change the `t()` functions in there to say whatever you want.

ADDITION:

A quick grep thru d7 suggests changing this...

```
/**
 * Returns HTML for the Powered by Drupal text.
 *
 * @ingroup themeable
 */
function theme_system_powered_by() {
  return '<span>' . t('Powered by <a href="@poweredby">Drupal</a>', array('@poweredby' => 'http://drupal.org')) . '</span>';
}

```

in a similar way as described above would accomplish what you want, but yes, you would need to edit some code to do it in your theme.

If that doesn't work, or you aren't confident enough to do that, you could just remove/disable the powered by drupal block itself and create another one with your own created by link in it.

---
Tags: blocks
---


# Question
Title: For Drupal 7 sub-domain installation is sites.php the same as 6's use of symbolic link folder?
I have a working Drupal 6 using a shared Drupal install on a shared Linux server. I've just installed D7. I'm not sure if sites.php is set up correctly (see below). And I can't find good information on this sites.php file to be sure I set it up correctly. This Drupal.org page describes the correct installation situation, but sadly does not mention sites.php (\>\_\<) This Drupal forum poster has the same "Server Not Found" error, but shows completely wrong sites.php example--the set up is not clear.

Is sites.php do the same thing that a symbolic link folder did in Drupal 6. Can I ignore this file?

My sites.php file,

```
 $sites['mondo7'] = 'mondo7.mydomain.com';

```

and I tried it the other way,

```
 $sites['mondo7.mydomain.com'] = 'mondo7';

```

Both show up "Server Not Found".

# Answer
> 3 votes
sites.php exists so you can fake out the normal multi-site operation, like mapping 'localhost' to 'foo.mysiteroolz.com'. Ideally you wouldn't use it in a production server.

In a live-to-the-internet site, you don't want to have sites.php (unless you specifically know why you do), and you want your subdomain to resolve to the same IP and directory as the domain. Then just have a subdirectory in /sites. So:

`drupal/sites/default/` will have settings.php and files for mydomain.com

`drupal/sites/mondo7.mydomain.com/` will have settings.php and files for mondo7.mydomain.com.

Then in your dev setup, you'd have a sites.php file that says something like `'localhost' => 'mondo7.mydomain.com'` This tells Drupal which site directory gets the attention when a request comes for localhost.

HTH.

# Answer
> 0 votes
The purpose of the site.php file is documented in example.site.php (the file that comes with the Drupal installation files).

> Drupal searches for an appropriate configuration directory based on the website's hostname and pathname. A detailed description of the rules for discovering the configuration directory can be found in the comment documentation in 'sites/default/default.settings.php'.
>
> This file allows you to define a set of aliases that map hostnames and pathnames to configuration directories. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. The aliases are defined in an associative array named $sites, which should look similar to the following:
>
> ```
> $sites = array( 'devexample.com' => 'example.com', 'localhost.example' => 'example.com', );
>
> ```
>
> The above array will cause Drupal to look for a directory named "example.com" in the sites directory whenever a request comes from "example.com", "devexample.com", or "localhost/example". **That is useful on development servers, where the domain name may not be the same as the domain of the live server. Since Drupal stores file paths into the database (files, system table, etc.) this will ensure the paths are correct while accessed on development servers.**

If you don't have a development site, you should not use the site.php file, and that is the reason the page you read doesn't have any reference to that file.

---
Tags: 7, subsites
---


# Question
Title: how to implement substring() in db_select statement
I am porting a drupal 6 module to drupal 7. I came across this SQL query:

```
SELECT count(*) AS total FROM {counter} WHERE SUBSTRING(counter_date,1,10)= '%s'

```

How to implement the same query in db\_select. db\_select() will have substring() in its condition clause.

# Answer
> 5 votes
A couple quick greps suggest something like this...

```
$query->where('SUBSTRING(counter_date,1,10) = :arg', array(':arg' => $arg));

```

...should do it.

# Answer
> 3 votes
The alternative, if `$query` is the object returned from `db_select()`, is to use expressions as reported in Dynamic queries, Expressions.

```
$substring_alias = $query->addExpression('SUBSTRING(counter_date,1,10)', 'counter_substring');

```

`$substring_alias` can be used then in `$query->condition()`, such as in the following code.

```
$query->condition($substring_alias, $value);

```

In this way you can use the condition together other ones. By default, conditions are ANDed together; if you need to OR them together, you can use the following code.

```
$query->condition(db_or()
  ->condition($substring_alias, $value)
  ->condition(/* the other condition */)
);

```

The value returned from `$query->addExpression()` is the alias effectively used for the expression; the method tries to use the alias passed as second argument, but if that alias is already used, it will generate a new alias.

`$query->addExpression('SUBSTRING(counter_date,1,10)', 'counter_substring')` alone is equivalent to the following select statement.

```
SELECT SUBSTRING(counter_date,1,10) AS counter_substring

```

In `$query->addExpression('SUBSTRING(counter_date,1,10)', 'counter_substring')`, I supposed there is not a "counter\_substring" field defined for the database table; in the case there is that field, you should use a different alias. The documentation says the method is able to use a different alias, if the proposed one is already in use, but it doesn't say what the behavior of the method is, when there is a field with that exact name; I would not expect the method verifies the alias is not a field name, before to use it.

---
Tags: 7, database
---


# Question
Title: How do I get Drupal to load a node instead of looking for the index.php outside of drupal in a subfolder
I inherited a site that has a lot of manually created html/php files in subfolders outside of Drupal. In other words, not as nodes, but static html/php fiels (leading of from the site root). I would like to move many of them inside Drupal as nodes because they are just some basic html/php. However, when I create a node using the same alias, it continues to load the old static html/php page. (I have flushed cache, both local and in drupal). Thoughts?

# Answer
> 1 votes
You'll need to remove the original file, or make it unreadable by your webserver. Drupal is basically a big 404-handler; if the file exists it will get loaded before the webserver looks for the default index.php which then bootstraps Drupal.

That, or check to make sure you don't have APC or similar opcode cache installed.

# Answer
> 0 votes
Have you checked for redirects in your `.htaccess` file? It's a possibility they are being redirected before Drupal even starts bootstrapping.

Try moving this file away form your webroot (back it up first, just in case) and then get a fresh `.htaccess` file from whichever Drupal 6 version you are running.

---
Tags: 6, path-aliases
---


title: Access denied on Password Recovery page

text:
# Question
Title: Access denied on Password Recovery page
I tried to customize the "password recovery" page under Drupal 7, based on this tutorial : http://www.absolutecross.com/tutorials/drupal/theming-the-user-account-page-in-drupal. I did so for the register and edit page, and it works ok.

However, for this page, I run into a problem. When the page "/user/pass" (is that the standard url by the way ?) is called, I ran into an access denied page.

I browse through the permissions : nothing in there to allow/deny access to this page. I also use loginToboggan, disabled it for a while, to no avail.

Any idea of what I could I have overlooked ? I am lost...

Thank you.

# Answer
> 1 votes
The password recovery page is at "/user/password", not "/user/pass".

I also get an Access Denied when visiting "/user/pass" on one of my sites, whether I'm logged in or not, so I think you can assume this is the expected behaviour for that particular path.

---
Tags: users
---


# Question
Title: How can I make search with a substring of a word?
I would like to search with only part of a word,not the whole word.For example when I search name of people,I would like to search only the first 3 letters of the Last Name,not the whole name.Now if I put on search only the first 3 letters I take no results.For the moment I am using the search api with apache solr(and perhaps views).Any suggestions please?

# Answer
> 5 votes
Add ngramfilter to text type definition in schema.xml in solr config directory.

```
<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="25" />

```

---
Tags: search
---


title: How to add breadcrumb?

text:
# Question
Title: How to add breadcrumb?
How can I add breadcrumb to a page in my attendance module.

I have used the following hook, but it changed the breadcrumb for all pages in other modules also.

```
function attendance_init() {
// set the breadcrumb
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('People', 'group/node/'. arg(2) .'/people');
$breadcrumb[] = l('Attendance', 'group/node/'. arg(2) .'/people/attendance');
drupal_set_breadcrumb($breadcrumb);

}

```

# Answer
Could you get what you want from the Custom Breadcrumbs module?

> Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home \> User Blog \>2005 \> January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.
> 1 votes

# Answer
About breadcrumb If you want to change in a node you can use hook\_node\_view to change breadcrumb an you can check $node-\>tyoe

```
function hook_node_view($node)
{
   if($node->type=="page")
    {
       drupal_set_breadcrumb();
    }
}

```

if you want to use it in a page you can check arg or $\_GET\['q'\] in any of hook\_page Hope it can help you
> 1 votes

---
Tags: breadcrumbs, taxonomy-terms
---


# Question
Title: Getting "On Behalf Of" in ubercart email confirmation
I am using ubercart in my site. After making the payment we are getting two emails. One is for the user and another for admin. In the amin email I am getting "On Behalf of" and id of the developer who developed this app. How to change it.

Any help is greatly appreciated.

# Answer
> 1 votes
Try to look in modules folder, in

site root folder /sites/all/modules/ubercart/uc\_order/templates/uc-order--admin.tpl.php

---
Tags: ubercart, commerce
---


title: How to set new AUTO_INCREMENT value?

text:
# Question
Title: How to set new AUTO_INCREMENT value?
I have the following statement in my module code:

```
db_query("ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = :number", array(':number' => $start_value));

```

During SimpleTest I get the following error message:

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near ''20000'' at
line 1: ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = :value; Array (
[:value] => 20000 ) in _tripletex_add_invoice_log() (line 1769 of
/var/www/d7/sites/all/modules/tripletex/tripletex.module).

```

Why?

# Answer
> 11 votes
Parameter replacement only works for `WHERE` clauses, it won't work for the kind of query you're trying to run.

You need to insert `$start_value` directly into the query string. If that value comes from an un-trustworthy source then obviously you need to sanitise it and make sure it falls within the correct bounds yourself:

```
$start_value = (int)$start_value; // Make sure it's an integer

// Do any other checks you need to here (bounds checking, etc.)

// Build the query string and run it
$sql = "ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = $start_value";
db_query($sql);

```

---
Tags: 7, testing
---


# Question
Title: Content type with buttons such as "I'm going here" and "I have been here"
Is there a way to have a content type for a location (I've already set up the map part) so users can click a link and say whether they've been there or not and it will show on their profile as 'places visited' and 'places planning on going'.

Thanks

# Answer
> 2 votes
I would take a look at the Flag module for this. We have used this module for similar purposes with good results.

You should be able to set up “I'm going here” and “I have been here” as different "flags", and then enable these flags on the content types you need. This particular module integrates nicely with Views, Actions, and other Drupal mechanisms.

---
Tags: 7, users, nodes, location
---


title: Views node Theming

text:
# Question
Title: Views node Theming
I'm working on a site in Drupal 6, and I've created a page view as I wanted, and it displays in a table.

Unfortunately, the theme that I'm using has a sidebar Region which doesn't collapse even when it has no block in it. Due to this, I would like to take away the sidebar as I would like the table that renders my views to stretch across the content area.

Even though I've copied the theming information, I'm kind of confused of how to create a template to show the view in the page without the sidebar region.

Someone help.

Thank you

# Answer
> 1 votes
Here is a quick css trick that will hide the side bar in this page view :

1 Open firebug and inspect the body tag and find out the class with the name of your view ex :

In my case my view name is : page marque and I find in my body tag this :

```
<body class="not-front not-logged-in page-parmarque one-sidebar sidebar-left">

```

2 With firebug inspect the container of your sidebar id or class , suppose that your sidebar id = left-sidebar this piece of css code will resolve the problem :

```
.page-marque #left-sidebar{
    display:none;}

```

this will hide the sidebar only in your page view , replace .page-marque and #left-sidebar with your values

Or there is a solution with jQuery alternative for your case : add this code to a javascript file and add it to .info file and flush caches

```
<script type="text/javascript">
jQuery(document).ready(function(){
  if(window.location.pathname == "/property-listing"){
  jQuery("#content").css({"width":"auto"});
}
})
</script>

```

---
Tags: views, theming
---


# Question
Title: How to update the google fonts provided by @font-your-face module?
I have enabled the @font-your-face module. Then I'm able to use google fonts in my site. Problem is that the list of fonts in the google directory shows more than 500 fonts: fonts but I just have 300 fonts available.

I need a font called **Imprima**. Is there any way to include this one in the @font-your-face module.

The module is updated to the last version.

# Answer
> 2 votes
If you just updated to a new version, have you gone and re-imported all the fonts you need/want (step 2 below)? In D6 at least, the following worked here:

1. Install module, enable base and google apis.
2. Go to admin/settings/fontyourface and import google fonts -- 1449 fonts imported
3. Go to admin/build/themes/fontyourface and click browse -- 58 pages of 25 fonts displayed

and sure enough, Imprima is in there when you search.

---
Tags: theming
---


# Question
Title: boolean function to determine whether an commerce order id exists?
is there a boolean function that exists OOTB that allows you to determine if a commerce order id exists?

I'm trying to pass an order id and check if is actually an existing order regardless of order state.

# Answer
There isn't a function that returns only a boolean, but `commerce_order_load()` returns `FALSE` if no order is found so you can use it in an `if` statement quite happily:

```
if (commerce_order_load($order_id)) {
  // Order exists
}

```

If you want to be bit more militant about it you could use this:

```
if (commerce_order_load($order_id) !== FALSE) {
  // Order exists
}

```

But it shouldn't really make a difference.
> 3 votes

---
Tags: 7, commerce
---


# Question
Title: redirecting to url that will never complate
i used this code to redirect page to another

```
$path=$_SERVER['QUERY_STRING'];
$new_path= 'http://localhost/mysite/print/194?0=' . $path;
drupal_goto($new_path);

```

but when requesting that page this error show up:

and the url in the address bar is:
http://localhost/mysite/print/194?0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=0=f1=All&f2\[value\]\[year\]=&f2\[value\]\[month\]=
but when i print the $new\_path using drupal\_set\_message the url looks like correct one
Can you help me to solved it? thanks.

# Answer
> 1 votes
The biggest issue is that the query string should be passed in separate from the base URL itself, eg, it should be part of the $options array argument to `drupal_goto()`. Otherwise, as you've noticed, `drupal_goto()` doubles up a lot of times. If you fix that, I am fairly confident that you will get it to work.

Check out http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_goto/7 and http://api.drupal.org/api/drupal/includes%21common.inc/function/url/7 for more information on this.

---
Tags: 7, uri
---


title: Subclassing content type forms

text:
# Question
Title: Subclassing content type forms
I was wondering how would you guys approach a situation where your Drupal7 site required a couple of custom content type, yet most of the fields would be shared across them. What I mean resembles a typical object-oriented case of a super class and its subclasses.

I want it so that I can make the admin-side content filling easier for the owner of the site. I also assume that for me, as the author of the form it would be a great time-saver if I could base one on another.

Is it possible? Does it make sense? Or would you rather make one type with all possible fields merged onto one form, then tweak the suggestion template so that irrelevant parts are /shown/hidden upon changing a dropdown menu that specifies the subclass?

Anyone been through a similar problem?

# Answer
> Or would you rather make one type with all possible fields merged onto one form, then tweak the suggestion template so that irrelevant parts are /shown/hidden upon changing a dropdown menu that specifies the subclass?

If you're going the single-type route, here are two tips: Drupal Forms API supports conditions, check the docs; it might be useful to take a look at the Prepopulate module.
> 1 votes

# Answer
There's no way to use actual object-oriented inheritance. However, you can manage the field configurations in such a way that you attach them to multiple content types based on some flag--typically a content type-specific variable.

Using the Features module's Field export hooks (namely, `hook_field_default_fields()` and `hook_field_default_fields_alter()`), you can programmatically define fields for multiple types. In fact, once this issue lands, you can have a central definition for a field, then separate instance definitions to attach and configure that field for each content type.

For form changes in general, you could capture multiple node types in the same form alter logic to create common tweaks to certain nodes. In both cases, you might end up using code such as

```
if (variable_get($node->type . '_is_a_shape', FALSE)) {
  // Apply changes to form/data structure.
}

```
> 0 votes

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


# Question
Title: What file or data I should NOT give outsourcing developer for security when they need a copy site of my site?
I'm asking a outsourcing developer to modify some part of my site and then he needs the copy of my site as a test site.
My site is already working site and has users registered. What comes in mind first is deleting user table from database to protect the personal information.

And the what else I should NOT give the developer? I trust the one who works on my site of course. But in generally is there any files or database table that can be harmful if the third party obtains?

# Answer
> 1 votes
There are two places I would look:

1. Any credentials stored in places like the settings.php file which has database credentials and potentially other sensitive information. If it's not in settings.php (e.g. some sites use settings.local.php that is included into settings.php) then just be aware of that and who has access to it. There may be other credentials stored in other .php files.
2. Your database has a lot of potentially sensitive information in it. See this article about sanitizing the Drupal database backup for advice on what you may want to remove.

Also, if you trust them to write module or tpl files then you should trust them with your data. After all: they could make a mistake or add a back-door to the site to steal this information if they want it. I see both of the above suggestions as "best practices" regardless of who is doing the work. Everyone should remove credentials and sensitive database information prior to giving out copies of the information.

# Answer
> 2 votes
Deleting the user table might break features that rely on node authors or some other user information. Try setting every user's email to email@mail.com and their password to 'password'. You shouldn't give the settings.php file, since it has your database credentials and the cryptographic salt Drupal uses to hash users' passwords.

---
Tags: 6, database, migrations, security
---


title: Content Type admin-side UI

text:
# Question
Title: Content Type admin-side UI
I have a custom content type which has grown in fields count and all that UI hints and stuff. It now takes about 4-5 screens to scroll. I was wondering if anyone knows of a module/way that allows to re-organize the Add Content UI form into sections. For instance - I would like to have all head data (title, teaser text, description) on a separate tab, all taxonomy qualifiers on another one, all images and uploads on yet another one, etc.

I think such a re-organized way will be much more friendly for the client to fill up with info and to maintain as well.

Anyone? Artur

# Answer
> 0 votes
See the Multistep module. Although it is under development for Drupal 7.

# Answer
> 0 votes
If you're content with keeping the form as a single page and just want to be able to segment out the UI of what's on that screen a bit you might be able to use Field group as well.

(So the whole thing could be a single page but part broken out into horizontal/vertical tabs, accordions, etc.)

---
Tags: 7, routes, nodes
---


# Question
Title: Is it possible to make the output of a taxonomy reference field with multiple values grammatical?
I have a taxonomy reference field that allows for multiple values.

In Views, when displaying this field, I have configured it as follows:

I was wondering if it's possible to somehow configure Views to make this output grammatically:

**EXAMPLE 1**

* Field label: I like:
* Values in node: apples, bananas
* Views current output: I like apples, bananas.
* Desired output: I like apples and bananas.

**EXAMPLE 2**

* Field label: I like:
* Values in node: apples, bananas, pears
* Views current output: I like apples, bananas, pears.
* Desired output: I like apples, bananas, and pears.

# Answer
> 1 votes
I did this in D6 using a CCK field formatter and using the Multiple Group Values.

What you want to do is inform Drupal essentially of a new radio option for "Display Type" that formats the output how you want for the collection of elements.

Again my solution is for D6, but you basically make a field formatter in D7 as well ...

```
# expose the formatter to ckk using a hook
function MYMODULE_field_formatter_info() {
  return array(
    'compressed_days_formatter' => array(
      'label' => t('Compressed Days'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'description' => t('Displays a listing of days in a month with commas'),
      'multiple values' => CONTENT_HANDLE_MODULE,
    ),
  );
}

# define our theme function
# this turns array('2011-12-03', '2011-12-04', '2011-12-05')
# into say "december 03,04,05 2011".
# and stradles months / years OK by outputting multiple lines.
function theme_formatter_compressed_days_formatter($elements) {
  $output = array();
  foreach (element_children($elements) as $k) {
    $day = $elements[$k]['#item']['value'];
    $ts = strtotime($day);
    $Y = date('Y', $ts);
    $M = date('M', $ts);
    $d = date('d', $ts);
    $dates[$Y][$M][]=$d;
  }
  foreach ($dates as $year => $months) {
    foreach ($months as $month => $days) {
      $output []= $month.' '.implode(', ',$days).', '.$year;
    }
  }
  return implode('<br>',$output);
}

```

So I haven't done this in D7 (yet) ... but the approach would be the same. You'd just implode most of your elements with commas, and then the last item you tack on your 'and' as-needed.

A hacky-er way to do this is probably with an alter hook in views\_pre\_render() that examines each result and looks for the last comma and replaces it with an "and". That would work but its more cryptic and sloppy ... I think you really want a formatter here.

---
Tags: 7, views
---


title: Specifying a CSS class for a view

text:
# Question
Title: Specifying a CSS class for a view
In Drupal 7 using Views 7.x-3.3, I've specified a CSS class for the view under Advanced -\> Other -\> CSS class. I have my CSS class defined in my custom theme CSS file as...

TABLE.listView { border: 0; border-spacing: 0; margin: 10px 0; width: 100%; }

but the view is not using the class. When I look in FireBug I see it using a class "views-table cols-5". If I overwrite that class in FireBug with the one I created in the theme, the view table is styled the way I want it to look. How can I get views to use the CSS class I've specified? All I'm trying to do is get the table styled the way I want it to look.

# Answer
> 3 votes
Given the commentary above, all you should need to do is cascade your class/table, eg, something along the lines of...

```
.listView table {
  border: 0;
  border-spacing: 0;
  margin: 10px 0;
  width: 100%;
}

```

---
Tags: 7, views, theming
---


# Question
Title: drupal 7: trying to make use of Compressing JS and CSS causes Major Error
hi I want to enable the compression of my JS and CSS to speed up my drupal site, but when I tick these boxes my site breaks completely. I can't even reload the performance page to remove the tick!! Thankfully I leanred this sometime back so I open the perf page twice tick on one and apply, see error then save the other loaded page which resets the situation.

error message for either CSS or JS tick is

```
The website encountered an unexpected error. Please try again later.

```

Also I CAN set these ticks on my localhost verion of the site, I get this problem on the hosted site.

anyone know why I can't use these features?

edit. Also there is nothing in the logs when I get back into the site.

error below was shown when warnings and error were turned on to display

```
Error
Error message
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'WATCHDOG_ERR' for column 'severity' at row 1: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => The specified file %file could not be copied to %destination. [:db_insert_placeholder_3] => a:2:{s:5:"%file";s:22:"temporary://fileFTC3lH";s:12:"%destination";s:64:"public://css/css_jZfSPTZv1KVtNJ48SyQgcHuPQjmI4wt9aqGhI5N-Vyg.css";} [:db_insert_placeholder_4] => WATCHDOG_ERR [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.martynazoltaszek.com/admin/config/development/performance [:db_insert_placeholder_7] => http://www.martynazoltaszek.com/admin/config/development/performance [:db_insert_placeholder_8] => 87.74.16.7 [:db_insert_placeholder_9] => 1334073447 ) in dblog_watchdog() (line 157 of /home/martynaz/public_html/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.

```

# Answer
> 1 votes
There is probably an error with the file-system? Go to admin/config/media/file-system, check the settings or just hit the save button again. But backup your site befor you do this. Have you tried to upload a file? Do you get any other cache / temp error? Did you clear the cache?

# Answer
> 0 votes
Something is really odd with your symptoms. If you look at the code for `_drupal_log_error`, you will see that there is a `watchdog()` that logs a PHP error in the dblog. So, you really should be seeing something there. You should also be seeing some other messages that pinpoint the exact location of the error.

Are you actually getting a maintenance page? If you look at the code (which is the only source of that string), it should be appearing in one.

This are all shots in the dark, but ...

Make sure your messages are enabled, and make sure dblog is enabled. Make sure you have nothing major (ie, red) on your status report page.

Make the error happen and then manually look at the `{watchdog}` table and look for the error. I would also check the Apache `error_log`. One of these two really should have the error message in it.

# Answer
> 0 votes
To fix the Database Logging or dblog module, compare these two things on your local and remote database installs:

* database user permissions for the site's database (can it create, modify tables, etc on both installs?)
* watchdog table's create statement, something like `show create table watchdog` ought to work on MySQL

Once you have this fixed, post the errors you see in the watchdog logs.

---
Tags: performance
---


# Question
Title: How to retrieve my module settings (those defined in hook_settings_form)
I need to validate a request in my custom payment method module for Drupal Commerce and i need to retrieve a value that was set by the user in the admin panel, how can i do that?

I basically need a way to get back the settings defined in the implementation of `hook_settings_form()`

EDIT - this is where i define the settings for my payment method

```
/**
 * Payment method callback: settings form.
 */
function commerce_xpay_settings_form($settings = NULL) {
  $form = array();

  // Merge default settings into the stored settings array.
  $default_currency = variable_get('commerce_default_currency', 'USD');
  $xpay_languages = array(
    'ITA' => t('Italian'),
    'ENG' => t('English'),
    // '3' => t('Espagnol'),
    // '4' => t('Francaais'),
    // '5' => t('Deutsch'),
  );
  $xpay_currencies = array(
    // '1' => 'USD (US Dollar $)',
    // '2' => 'GBP (Pound Sterling ¬£)',
    // '71' => 'JPY (Japanese Yen)',
    // '71' => 'HKD (Hong Kong Dollar)',
    '978' => 'EUR (Euro ‚€)',
    // '234' => 'BRL Real',
  );

  $currency = in_array($default_currency, array_keys($xpay_currencies)) ? $default_currency : '978';
  /* The hardcoded values for commerce_xpay_tid and commerce_xpay_mac are the
   * standard values for the
   * test server, keep them while testing, documentation for x-pay is horrible */
  $settings = (array) $settings + array(
    'commerce_xpay_tid' => 'T04_000000000005',
    'commerce_xpay_mac' => 'AA88CCEWDKLSDJD3921ZZ',
    'commerce_xpay_mode' => 'TEST',
    'commerce_xpay_action_code' => 'VERI',
    'commerce_xpay_language' => 'ITA',
    'commerce_xpay_currency' => $currency,
    'commerce_xpay_method_title' => t('Credit card on a secure server:'),
    'commerce_xpay_method_title_icons' => TRUE,
    'commerce_xpay_checkout_button' => t('Submit Order'),
  );

  $form['commerce_xpay_tid'] = array(
    '#type' => 'textfield',
    '#title' => t('Terminal ID'),
    '#description' => t('Your Xpay teminal id.'),
    '#default_value' => $settings['commerce_xpay_tid'],
    '#size' => 25,
  );

  $form['commerce_xpay_mac'] = array(
    '#type' => 'textfield',
    '#title' => t('Mac Key'),
    '#description' => t('Your MAC key'),
    '#default_value' => $settings['commerce_xpay_mac'],
    '#size' => 25,
  );

  $form['commerce_xpay_mode'] = array(
    '#type' => 'select',
    '#title' => t('Mode'),
    '#description' => t('Select NORMAL form normal usage or TEST for testing pourposes'),
    '#options' => array(
      'test' => t('TEST'),
      'normal' => t('NORMAL'),
    ),
    '#default_value' => $settings['commerce_xpay_mode'],
  );

  $form['commerce_xpay_action_code'] = array(
    '#type' => 'select',
    '#title' => t('Action Code'),
    '#description' => t('Select the action code for the authorization request; from 21-02-2011 it has to be "VERI"'),
    '#options' => array(
      'VERI' => "VERI",
      'AUT' => "AUT",
    ),
    '#default_value' => $settings['commerce_xpay_action_code'],
  );

  $form['commerce_xpay_language'] = array(
    '#type' => 'select',
    '#title' => t('Language preference'),
    '#description' => t('Adjust language on XPAY pages.'),
    '#options' =>$xpay_languages,
    '#default_value' => $settings['commerce_xpay_language'],
  );

  $form['commerce_xpay_currency'] = array(
    '#type' => 'select',
    '#title' => t('Currency preference'),
    '#description' => t('Adjust currency used with XPAY.'),
    '#options' => $xpay_currencies,
    '#default_value' => $settings['commerce_xpay_currency'],
  );

  $form['commerce_xpay_method_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Payment method title'),
    '#default_value' => $settings['commerce_xpay_method_title'],
  );
  $form['commerce_xpay_method_title_icons'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show credit card icons beside the payment method title.'),
    '#default_value' => $settings['commerce_xpay_method_title_icons'],
  );
  $form['commerce_xpay_checkout_button'] = array(
    '#type' => 'textfield',
    '#title' => t('Order review submit button text'),
    '#description' => t('Provide XPAY specific text for the submit button on the order review page.'),
    '#default_value' => $settings['commerce_xpay_checkout_button'],
  );

  return $form;
}

```

# Answer
> 2 votes
The settings are available in `$payment_method['settings']`. The `$payment_method` variable is passed to almost all commerce payment hooks.

---
Tags: 7, commerce
---


# Question
Title: Filter unpublished nodes, even for Admin
How can I filter out unpublished nodes in a view even if the user viewing it is an administrator?

# Answer
Sound like you just want to switch the filter you are using from

```
Content: Published or admin
Filters out unpublished content if the current user cannot view it.

```

to

```
Content: Published
Whether or not the content is published.

```
> 1 votes

---
Tags: views
---


# Question
Title: Change submit button to be ajax using jQuery on forget password does not work
I want to change submit button on forget password to be ajax to display the form as a pop up I use this validation

```
jQuery('#user-pass').validate({
        rules:{
            "name":{
                required:true,
                email: true
                }
            },
            submitHandler: function(form){
                jQuery.ajax({
                      type: "POST",
                      url: jQuery("#basPath").val() +"ajax/check-login",
                      data:  jQuery("#user-pass").serialize(),
                      dataType:"html",
                      success: function(msg)
                      {
                        if(msg == "Invalid Email")
                        {
                            return false;
                        }

                        else
                        {
                            jQuery("#user-pass").submit(function() {
                              alert('Handler for .submit() called.');
                              return false;
                            });
                        }
                      }
                 });
            }
        });

```

but no email is sending Is this right or I have to make something else (I am using Drupal 7.12)

# Answer
I found a solution I want to share with you I use

```
jQuery(form).ajaxSubmit();

```

an remove this

```
jQuery("#user-pass").submit(function() {
                              alert('Handler for .submit() called.');
                              return false;
                            });

```

and it solve the problem I hope it can help you
> 0 votes

---
Tags: ajax
---


title: Drupal Database Encryption

text:
# Question
Title: Drupal Database Encryption
I am seriously looking for a solution to encrypt at least some of the tables in my Drupal 7 database.

I'm totally suspicious about my hosting providers, I really don't want my user's data and also my business information to be visible at all.

Are there any solutions for database encryption? I don't want to buy a VPS.

# Answer
In short, unless you are the only person with physical access to the server, you are not safe, there is no way you can do this with reasonable effort, a VPS makes no difference.

If you could deploy something like full disc encryption which was only unlocked when you logged in to the system, your provider could still have virtualized the entire server, and not encrypt it anyway, only tell you they have.

Even if you somehow managed to safely encrypt the database, it needs to become readable at the server side at *some point*, or your server couldn't possibly serve the data.

Either this means that your webserver actually holds the decryption key, making it at most moderately complicated to copy it. You *could* require the key to be entered every time your http-deamon starts and store it only in RAM, but again, if your host is in a virtual machine you are immediately screwed, and a determined attacker could steal the key from RAM even from physical ram.

I could go on, but the gist is, you can't do what you want without a lot of resources, mainly physical servers in a locked serverrack.
> 3 votes

# Answer
Long story cut short, the servers are owned by your host therefore they can access the data at any time they so wish.

As mentioned, any encryption methods will need decryption keys/methods which will also have to be stored in your files..on the server.

You could check out Encryption or AES, but at the end of the day...your provider will be able to access the data regardless.
> 3 votes

---
Tags: 7, database, security
---


title: forum post editor problem Wysiwyg

text:
# Question
Title: forum post editor problem Wysiwyg
hello i have my local server setup and everything works great so i migrate from local to webservever

then something stop working.

My permissions in some way resetted and the problem is that even when i have enable and all correct permissions the editor not working.. i cannot even see enable-disable rich text

also overlay not working something happen and stopped.

But the main problem is the tinymce not working even when setup it correct from my local server (i see the setting side by side and choose them) but i again doesnt work any thoughts.

# Answer
> 0 votes
**Answered in comment by Dimitris B:**

Found answer, in administrator -\> configuration at performance section i disable Aggregate JavaScript files which i had enabled, so i realize that i had a problem in my js code so i need to check it up, but after i disable it everything works perfect.

---
Tags: 7, nodes
---


title: jquery media not show player

text:
# Question
Title: jquery media not show player
I'm trying to use jQuery Media, but it's not working. I am getting the following error in Firebug:

> "NetworkError: 404 Not Found - http:// demo.dolphin-sch.ir/nagara/fa/sites/default/files/mediaplayer/player.swf?file=http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3"

You can see the error on my website:

> http://demo.dolphin-sch.ir/nagara/fa/content/abc

First I enable jQuery Media (version 6.x-1.4-beta1) and jQ (version 6.x-1.2) and then upload the JW FLV Player to `sites/default/files/mediaplayer/player.swf`. Next I change my `template.php` and create a `filefield_file.tpl.php` file. Lastly, I set a media class `.field-field-flash-file a, .filefield-file-audio a` but it's still not working.

Can anyone help?

# Answer
> 0 votes
The two locations specified for `sites/default/files` are different in your example:

First part: http://demo.dolphin-sch.ir/nagara/fa/sites/default/files/mediaplayer/player.swf?file=

Second part: http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3

I'd check your paths are set correctly everywhere.

**EDIT:**

This link works fine:

http://demo.dolphin-sch.ir/nagara/sites/default/files/mediaplayer/player.swf?file=http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3

---
Tags: theming, javascript, files
---


# Question
Title: How to get rid of 'security updates available' warnings?
I am using the ShareThis module on my website. Unfortunately, recent release 2.3 is flagged as a security update, but it is has a major bug (settings can't be saved). I have reverted to release 2.2.

The consequence is that 'security updates available' warnings are displayed all the time in administration screens. Is it possible to get rid of them? I tried to find an option, but could not find any.

# Answer
> 5 votes
I had a similar problem recently (see How do I avoid checking for updates for a specific module?) and managed to get around it using `hook_update_projects_alter()`. You can use it to easily remove any module that you don't want to be part of the update process:

```
function MYMODULE_update_projects_alter(&$projects) {
  $blacklist = array(
    'sharethis',
    // Any others you might want
  );

  foreach ($blacklist as $module) {
    unset($projects[$module]);
  }
}

```

As Drupal no longer considers any module you put in the `$blacklist` array as one that needs to be updated, you should stop getting the security warning.

It would probably be a good idea to keep an eye on the progress of the bug in the ShareThis module so that you can remove this restriction when possible.

# Answer
> 4 votes
I'd say the *right* way to get rid of it is to fix the bug (e.g. by reviewing the patch in that issue) and deploying that patch on your server.

The vulnerability in the module is pretty serious. It would allow an attacker to take over your site. You don't want to be running an outdated version of the module if at all possible.

---
Tags: 7, updating, security
---


# Question
Title: Appending markup to privatemsg message body
First, a little background info:

I'm running privatemsg 7.x-1.2 across several sites running on a single D7 codebase. I have all of the privatemsg tables in one database, which is accessed by all of the sites as to keep private messages synchronised between them.

To enhance that little setup, what I would like to do is manipulate the message body at the time of insertion/saving to append a "This message was sent via \[site name\]" line at the very end of each message. This is how I achieved it at first:

```
function global_privatemsg_message_presave_alter(&$message) {
    $message->body .= "<div class=\"sent-via\">(". t("Sent via !site_link", array('!site_link' => get_site_link())) .")</div>";
}

```

That worked well except I overlooked the fact that hook\_privatemsg\_presave\_alter takes place prior to the input filter being applied, so if the user sends their message as "Filtered HTML" or "Plain text", the 'sent-via' gets thrown out.

So, what I'm looking for is a reliable way of appending markup to the message body, or even introducing a new template variable that I can populate accordingly, without it being mangled by input filters (the result of Drupal's check\_markup, I suppose).

Preferably I want to do this entirely within the constraints of the Privatemsg module API, but I appreciate that might be asking for the impossible.

Doable?

# Answer
> 3 votes
(I haven't used privatemsg) ... but sure it's doable because of a new feature in D7:

> Instead of attachments, private messages are fieldable and any number and combination of fields can be added to them.

So what you do is code up a custom module that defines a custom "sent\_by\_sitename" field that is a text `field_type`. Then in your presave hook you would just do:

```
$message->sent_by_sitename = 'some_sitename_in_your_multisite_install';

```

Then you could alter your message display to show this new field with a custom formatter that adds the markup and leading "This message sent by " markup.

I dont have the code to do this offhand (its probably about 30 lines). Here is a similar request of adding custom fields to the default user object in drupal -- your request is different regarding privatemsg but you probably will still use some of the same functions: add-properties-to-an-entity-hook-schema-alter

So in short:

* Define your custom field in your custom module, eg hook\_field\_info()
* on module\_enable() and module\_disable() attach your field to the message entity, eg field\_create\_field() and field\_create\_instance()
* alter your existing privatemsg API call to set this new field value instead of raw HTML.
* alter your privatemsg message display to show your new field with its associated field\_formatter to be at the bottom of the message display.

---
Tags: 7, hooks, privatemsg
---


# Question
Title: jQuery UI Dialog attempt to submit a form using AJAX redirects me to the actual form page instead of AJAX submitting
I have a form and I want to do the following

1. Click a link to popup a modal JqueryUI Dialog window
2. Load into this window, via AJAX, a Form
3. Submit the form via AJAX
4. Upon successful submission, Close the popup automatically

I have stages 1 and 2 working fine, but step 3 is causing me problems. If I create a form page which uses more or less the same code (different wrapper and function names but identical code) AJAX form submitting works just fine, so the problem seems to be that somehow the form HTML within the JQuery Dialog is not being processed to use AJAX.

Here is my code;

My Menu Item;

```
  // test ajax callback
  $items['teststuff/dialog-load/ajax'] = array(
'title' => t('Load Dialog AJAX callback'),
'type' => MENU_CALLBACK,
'page callback' => 'teststuff_dialog_load',
'access arguments' => array('access content'),
);

```

Form functions in my 'teststuff' module;

```
function teststuff_dialog_load () {
  // Get the form
  $form = drupal_get_form('teststuff_meal_entry3_form');

  return drupal_json_output(drupal_render($form));
}

function teststuff_meal_entry3_form($form, &$form_state) {
  $form = array();

  $form['date'] = array(
    '#type' => 'date_popup', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
    '#title' => 'Date and Time Eaten',
    '#default_value' => date("Y-m-d H:i:s"),
    '#date_format' => "Y-m-d H:i", // YY-MM-DD HH:MM
    '#date_label_position' => 'within', // See other available attributes and what they do in date_api_elements.inc
    '#date_increment' => 15, // Optional, used by the date_select and date_popup elements to increment minutes and seconds.
    '#date_year_range' => '-1:+1', // Optional, used to set the year range (back 3 years and forward 3 years is the default).
    '#required' => TRUE,
  );

  $form['meal_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Meal Name'),
    '#size' => 60,
    '#maxlength' => 100,
    '#description' => t('Enter a name for this meal'),
    '#required' => TRUE,
  );

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

 $form['actions']['submit']['#ajax'] = array(
       'callback' => 'teststuff_meal_entry3_form_ajax_callback',
       'wrapper' => 'teststuff-dialog-inner',
       'method' => 'replace',
       'effect' => 'fade',
     );

  return $form;
}

function teststuff_meal_entry3_form_submit($form, &$form_state) {
  // Validation is all good, so note the success
  $form_state['teststuff_meal_entry3_form_success'] = 1;
}

function teststuff_meal_entry3_form_ajax_callback(&$form, &$form_state) {
  if (!empty($form_state['teststuff_meal_entry3_form_success'])) {
    $confirmation = array(
      '#type' => 'markup',
      '#markup' => '

The form was successfully submitted

',);

    return $confirmation;
  }
  else {
    return $form;
  }
}
```

My JQuery

```
// Force Entry form to become a dialog and load info dynamically
// via AJAX
// Item has class 'myajax-popup'
(function($){
  Drupal.behaviors.make_dialog_myajax_popup = {
    attach: function (context, settings) {

      function ajaxCompleted (data) {
        // Parse Json
        // Add some stuff to your DOM.
        console.log(data);
        $('#teststuff-dialog-inner').html(data);
        Drupal.attachBehaviors($('#teststuff-dialog-inner'));
      }

      $('.myajax-popup').addClass("processed").click(function() {
        // Create a dialog
        var myDialog;

        // See if element already exists
        if ($("#teststuff-dialog-outer").length > 0) {
          // Dialog element exists, don't create
          myDialog = $("#teststuff-dialog-outer");
        }
        else {
          myDialog = $('');
          myDialog.appendTo('body');
        }

        $('#teststuff-dialog-inner').html('Initial content');

        myDialog.dialog({
            modal: true,
            width: 600,
            height: 'auto',
            hide: 'slide',
            title: "Title" });

        // Fire ajax to fill the dialog
        $.ajax({
          type: 'POST',
          url: '/teststuff/dialog-load/ajax',
          dataType: 'json',
          success: ajaxCompleted,
        });

        return false;
      });
    }
  };
})(jQuery);
```

And my link to open the popup;

```
<a href="#" class="mydialog-load">Popup LOAD into dialog</a>
```

Upon clicking Submit, The browser simply redirects to;

/teststuff/dialog-load/ajax (the callback link)

and the output on that page is the JSON

"\u003Cform action=\u0022/teststuff/dialog-load/ajax\u0022 ... snipped..."

Is anyone able to tell me what I am doing wrong and why my ajax submit (that works if the form is a full page form) is failing to do what I want it to do.

It's as if my call to Drupal.attachBehaviors() is not firing properly and not adding in the relevant ajax code. Although one of my own widget replacement behaviours is definitely running on the loaded form content.

I have managed to get the Dialog API module working. I also have the code working fine if I create a block on the page, initially hidden via CSS, but then turn it into a JQuery UI Dialog.

I just want this more dynamic behaviour to load in the form dynamically and prefer to avoid using extra modules if I can do so, especially when I am 66% of the way there! I'd also like to understand why I have the problem I have, rather than just taking the easier ways out.

# Answer
0 down vote

I finally got the answer to the problem! After days of struggling with it, I got a reply in the following post from Drupal expert, Jaypan: http://drupal.org/node/1517414.

I tweaked his answer a bit and set the settings after rendering the form like this:

$html = drupal\_render(drupal\_get\_form('myform'));

$javascript = drupal\_add\_js(NULL, NULL); $settings = FALSE;

if(isset($javascript\['settings'\])) { $settings = 'jQuery.extend(Drupal.settings, '. drupal\_json\_encode(call\_user\_func\_array('array\_merge\_recursive', $javascript\['settings'\]\['data'\])) .');'; }

$html .= $settings; print $html;

I hope this will fix your problem as well.
> 2 votes

---
Tags: ajax, javascript, forms
---


title: Creating list of content for each user

text:
# Question
Title: Creating list of content for each user
I have a custom content type named Movie.

Every user must have 2 lists of movies:

* Seen movies
* Not seen movies

For this purpose, I am using the Flag module to attach 2 links ("Seen" and "Unseen") on every movie page; with those, users can add the corresponding movie to their list.

I successfully made the two lists using the Views modules; users can see them when they are logged-in.

What I need is allowing users to see the movie lists of other users. How can I achieve this?

The "seen" and "unseen" lists should be mutually exclusive; if a movie is in the "Seen" list for user A, it cannot simultaneously be in the "Unseen" list for the same user.

How can I do this? Is there any other module, apart the Flag module, that could help me?

I am using Drupal 7.

# Answer
> 1 votes
Rather than using a filter like "current user" which would display uniquely for the logged in user, you will need to attach the view to each members profile with a "contextual filter" (under advanced on the right hand side). Use "User: Uid", then select"Provide default value" and "User ID from URL".

The above will mean that each view is unique to the user profile and any user can see another users list by going to their profile page.

---
Tags: 7, users, flags
---


title: Superfish Menu override CSS

text:
# Question
Title: Superfish Menu override CSS
I am using superfish menu module with drupal 7.7 and I can't figure out how to override the CSS in *space.css* or any other superfish stylesheet. If anyone knows how to, please share your input.

# Answer
> 2 votes
It supposed that the module has his own css, you need to edit those files but that is not a solution.

I recommend you to use some debugging tool like firebug and check what css you need to edit. Then write the css changes in your theme css file. With this logic if you update the module you will not loose all your custom changes.

# Answer
> 1 votes
I'd go with @byroncorrales answer and suggest that you use firebug or any web development tool to identify the styles that you need to modify. Also I believe that you have read the superfish module documentation and are adding the custom styles using the **Extra CSS Class(es)** and the **Extra CSS**. Apparently its merely a matter of CSS *precedence* and *specificity* that's giving you the trouble of not being able to override the CSS. You could refer this link to understand more on the issue and do some searching to identify and fix the issue as its been explained well in multiple places on multiple occassions.

# Answer
> 0 votes
In case you have an HTML already up and running; you can Select the Style option as "NONE" and just place your CSS in style.css of your custom theme. If the CSS is written properly it will work seamlessly for superfish Menus, with just a few tweaks needed.

---
Tags: routes, theming, navigation
---


title: Migration module and taxonomy terms

text:
# Question
Title: Migration module and taxonomy terms
I am attempting to use the migrate module to bring in data from another web application. There are several fields that are related and the first one I'm working with is languages. I can import the languages as taxonomy terms without problems. The BiblioMigration class imports most of the data without problems also. Unfortunately, no matter what I seem to do it fails to import anything into the "field\_biblio\_language" field. I have manually edited and created a node and placed a value into this field and it works fine. It is just the import that seems to produce nothing. According to the detail section for the Biblio Migration the language field is properly mapped. I have attempted to structure the code around this in several different ways but always end up with nothing. I have even attempted to pass a default value and it still fails to populate the table. Any help would be much appreciated.

```
class LanguageMigration extends Migration {
  public function __construct() {
    parent::__construct();

    $this->description = t('Migrate languages from the source database to taxonomy terms');

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'name' => array('type' => 'varchar',
                           'length' => 255,
                           'not null' => TRUE,
                           'description' => 'Language',
                          )
        ),
        MigrateDestinationTerm::getKeySchema()
      );

    $query = db_select('matrix_language', 'l')
             ->fields('l', array('id', 'name'));

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

    // Set up our destination - terms in the migrate_example_beer_styles vocabulary
    $this->destination = new MigrateDestinationTerm('language');
    $this->addFieldMapping('name', 'name');

  }
}

class BiblioMigration extends Migration {
  public function __construct() {
    // Put the migration into a group for each content type
    parent::__construct(MigrateGroup::getInstance('bibliographia'));

    // Query the original database
    $query = db_select('matrix_biblio', 'biblio')
      ->fields('biblio', array(
        'id',
        'primaryauthor',
        'role',
        'additionalauthors',
        'title',
        'titlealphaorder',
        'publishedin',
        'publisher',
        'citation',
        'languageid',
        'date',
        'notes',
        'bibliotypeid',
        'sourcetypeid',
        'publicationstatus',
        'archivelocation',
        'created',
        'lastmodified',
        'lastmodifiedby',
        'adminnotes',
        'placeofpublication',
        'dateofpublicationnote',
        'hide',
      ));
      $query->orderBy('id', 'DESC');

    // Define our original database query results as our source
    $this->source = new MigrateSourceSQL($query);

    // Define our new content type as our destination
    $this->destination = new MigrateDestinationNode('bibliographia');

    // Map the node id to the id field in our original database, this mapping is needed for rollbacks
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'alias' => 'biblio',
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    // Map our fields desitination -> source
    $this->addFieldMapping('field_biblio_primary_author', 'primaryauthor');
    $this->addFieldMapping('field_biblio_role', 'role');
    $this->addFieldMapping('field_biblio_additional_authors', 'additionalauthors');
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('field_biblio_sorting_title', 'titlealphaorder');
    $this->addFieldMapping('field_biblio_published_in', 'publishedin');
    $this->addFieldMapping('field_biblio_publisher', 'publisher');
    $this->addFieldMapping('field_biblio_citation', 'citation');
    //$this->addFieldMapping('field_biblio_language', 'languageid');

       $this->addFieldMapping('field_biblio_language', 'languageid')
            ->sourceMigration('Language')
            ->arguments(array('source_type' => 'tid'));

    $this->addFieldMapping('field_biblio_date', 'date');
    $this->addFieldMapping('field_biblio_notes', 'notes');
    $this->addFieldMapping('field_biblio_publication_type', 'bibliotypeid');
    $this->addFieldMapping('field_biblio_source_type', 'sourcetypeid');
    $this->addFieldMapping('field_biblio_publication_status', 'publicationstatus');
    $this->addFieldMapping('field_biblio_archive_location', 'archivelocation');
    $this->addFieldMapping('field_biblio_record_created', 'created');
    $this->addFieldMapping('field_biblio_last_modified', 'lastmodified');
    $this->addFieldMapping('field_biblio_last_modified_by', 'lastmodifiedby');
    $this->addFieldMapping('field_biblio_admin_notes', 'adminnotes');
    $this->addFieldMapping('field_biblio_place_publication', 'placeofpublication');
    $this->addFieldMapping('field_biblio_date_publication', 'dateofpublicationnote');
    $this->addFieldMapping('field_biblio_hide', 'hide');
  }

}

```

# Answer
> 3 votes
I think you need to define the languageid (id) as MigrateSQLMap identifier (instead of the name) in the LanguageMigration. With the name the mapping is not possible. The rest seems correct:

```
  $this->map = new MigrateSQLMap($this->machineName,
        array(
          'id' => array('type' => 'int',
                           'length' => 10,
                           'not null' => TRUE,
                           'description' => 'Language',
                          )
        ),
        MigrateDestinationTerm::getKeySchema()
  );

```

---
Tags: taxonomy-terms, migrations
---


# Question
Title: What are costs/benefits of integrating Phing, Jenkins together with Drupal?
I would like to improve my testing environment automation in order to reduce effort needed for quality assurance tasks.

I heard about Phing and Jenkins and read overview information but still I am not convinced it is worth investing the set up effort currently.

Can you explain the costs and benefits of installing Phing, Jenkins based continous integration environment while I am using Drupal, Drush, Git, Simpletest and bash scripts already in dev, staging, production set up ?

# Answer
> 5 votes
Ok, as for being a fan myself of continuous integration, I can assure you virtualisation is very handy to control the testing environment. I have built myself a CI setup, forking off from a wonderful package called quickstart. This package depends on Virtual-Box or other VM software, it is basically a Ubuntu made for Drupal with a pre-set up lamp architecture, pre-configured debugging and editors, profilers, etc.

I have installed Jenkins and phing on top of quickstart, and can assure you it is quite low cost($0), quite low hassle. Any one can co-opt in with me on most any project quite easily, the whole dev environnement is reproduced and it comes with quite a few tools by default, and quite a few I have myself upgraded.

Now, the way we use jenkins is most certainly not pure CI, it just run the tests when we commit, then we shut down the thing and forget about it. It could be used for notifications and documentation generation, and on some projects I do generate some code metrics but the main thing I also cared about in my setup was testing. One clear advantage when using a vm software for testing is it can easily be reproduced used to run the tests elsewhere or even on different systems and configurations, you always have control over the environnement (memory, processor usage, peripheral ressources, etc..)

In most projects I contributed on, testing is done before staging I guess this may be different depending on the project managers.

PS: Another thing to consider, in a true testing environnment you would tend to try and reproduce your server setup and load as much as possible. Our projects are hosted on Cent-OS and obviously we don\`t quite follow up to the rules on this aspect either, quickastart is Ubuntu based. So far have not had any problems, and as a bonus has many other features pre-configured for rapid Drupal application prototyping and developpment.

Happy CI'ing!

# Answer
> 1 votes
Where i am working Jenkins is configured and it is very useful.

When the code goes on the development server or live, the coder report will execute and will show all the coding reports by mail. Every user has their login so you can easily identify who added the buggy code.

Coder is one example you can run any number of events on that time as running your testcases when code goes up or run a selenium script.

---
Tags: 7
---


# Question
Title: How can I create a web form automatically when an organic group is created?
I would like to automatically create a webform when a new organic group node is created.

The webform should have predefined fields and trigger an email to the group administrator or a user in the group with a predetermined role. Alternatively it could email an address filled out in a cck field on the group content type.

I tried using og\_webform but couldn't figure out how to get it to create webforms for each group.

# Answer
> 1 votes
There is probably multiple was to this. The way I see it is a custom module.

You want to use hook\_nodeapi(&$node, $op) in Drupal 6, hook\_node\_insert($node) in Drupal 7.

You code would look like something like this

```
CUSTOM_MODULE_NAME_nodeapi(&node, $op) {
  switch ($op) {
    case 'insert':
       if ($node->type == 'group') {
         global $user;

         // Create new object.
         $node = new stdClass();

         // Set desired data and metadata as members in object.
         $node->type = 'predefine_webform_with_predefine_fields';
         $node->uid = $user->uid;
         $node->title = 'node title';
         $node->body = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...';
         //... prefill other cck fields

         // Save the node
         node_save($node);

       }
       break;
     }
   }
}

```

(Code should look the same for Drupal 7, minus the switch case)

# Answer
> 0 votes
To create a node programmatically , on some specific action we have to make some changes in node.module

on line no. 874, find node\_save($node) suppose you have a situation where you want to create a node from specific content type i.e. 'page' then. and programmatically node is

story type the code will be

```
    if($node->type=="page")
         {
    $node_new = new StdClass();
            //creating a bare node

    $node_new->type = 'story ';
    //giving it type

    $node_new->status = 1;
    //give it a published staus

    $node_new->title = "This is story title";
    //gives title

    $node_new->body = "This is story  body";
    //gives body

    node_save($node_new);

    //save it and give it the rest of the attributes
    //drupal_set_message('Automated '.$node_new->type.'Created');
}

```

Click Here to view original post

---
Tags: 6, organic-groups, webforms
---


# Question
Title: Using Flags to remember not only the node, but also its attributes
In our current development, running with Drupal 7, we need to let the end-user bookmark some products within a "catalog". We will use the flag module for this.

However, we would like the flag to remember not only the products, but its variants. Not only the node/entity itself, but also the "attributes" selected by the user.
i.e. : bookmark a T-shirt in such size / such color.

Is there a "drupal way" to do this ? Do I need to use an extra or different module ?

Thank you.

# Answer
> 1 votes
You could try some Rules trickery and save the attributes data to the users profile upon the flag action. However, I really think you will be best going down the custom module route because it is rather specific.

A very basic outline of the module would be something like the below:

1. Create your .info file to provide Drupal the details of your custom module
2. Create a .install file to create a db schema to contain the additional data, ensure you include a fcid row (to reference to the flag "flag\_content" table).
3. Create your .module file with function which hooks into the flag actions with appropriate if statements to refine the scope to these products. In this function you will want to save the additional "attributes" data to your new db table with a reference to the fcid to tie them up.
4. While in your .module file, if flag exists you will also want to perform a hook\_form\_alter on the products to change the default values to that which has been stored in the database.

I know my answer is very brief with regards to build the module but that is a bit beyond the scope of an answer here and I think that highlights the Drupal Way for what you will need.

---
Tags: flags
---


# Question
Title: Can Drupal be used for hierarchical multi-site?
Can you use Drupal to make a site hierarchy? The main reason would be managing permissions and general connections between sub sites, like the following one:

```
                       Site 1
        Site 2         Site 3         Site 4 …
    Site 5   Site 6                   Site 7 …

```

# Answer
This is a very vague question in that it doesn't give any semblance of the relation between the sites, or how they link to each other.

There are at least 3 different ways to make a unified site using multiple domains/subdomains using drupal:

1) Organic Group/Taxonomy/User based subdomains.

Each Group, Primary Taxonomy, or User gets their own subdomain, and their content is listed there. Cross domain login issues are relatively mild, and just a matter of fixing the cookie domain as .domain.name, where the subdomains would be group.domain.name or user.domain.name or term.domain.name.

2) Domain Access based domains

This is more an "affiliated network of sites" concept. Content is assigned to a specific site, and can be shared among all sites, or specific only to one. You link sites together using modules like Views as you can select content in any way you please, and give each site an individual look, or maintain a more consistent network theme. This can be implemented either as domains or subdomains, so cross-domain login issues are possible here, and can be difficult to mitigate effectively if you're trying to give an integrated feel. SSO is one possible way to solve the issue, but other tweaks, such as pulling the login id across domain boundaries is also possible. (This takes a little bit of technical wizardry)

3) Drupal sites based on a single install

All the sites share a code base, but each has their own database. Automated links between the sites would need to be done through communication channels like RSS or RPC, or else maintained manually. As the user databases are separate, there are no common logins across sites. SSO is probably a must in this case.

What solution fits your specific needs is not apparent from the question you're asking here, so please narrow the scope of your question by providing details as to what you mean by "site hierarchy". What specifically makes otherwise unrelated host names (or domain names) into a hierarchy?
> 4 votes

---
Tags: 7, multi-sites
---


title: Display and edit user info

text:
# Question
Title: Display and edit user info
When a user logs in, I'd like him to see his profile info (name, address) with a link to a form to edit that info.
I thought this should be a trivial task, because it is something needed on almost every site that allows users to register. Yet, I failed to get anywhere after a couple of hours of trying and searching.

What I have now is a view (using the views module) that displays a list of all users where each one has a link to the edit page. But I only want a user to see and edit his own stuff ...

# Answer
You may put template for user page like `user-profile.tpl.php` This template is used when viewing a registered member's profile page,

e.g., example.com/user/123. 123 being the users ID.

Available variables:

`$user_profile`: An array of profile items. Use render() to print them. Field variables: for each field instance attached to the user a corresponding variable is defined; e.g., $user-\>field\_example has a variable $field\_example defined. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language, e.g. $user-\>field\_example\['en'\], thus overriding any language negotiation rule that was previously applied.

**OR**

use `hook_menu_link_alter`

```
function hook_menu_link_alter(&$item) {
  // Make all new admin links hidden (a.k.a disabled).
  if (strpos($item['link_path'], 'admin') === 0 && empty($item['mlid'])) {
    $item['hidden'] = 1;
  }
  // Flag a link to be altered by hook_translated_menu_link_alter().
  if ($item['link_path'] == 'devel/cache/clear') {
    $item['options']['alter'] = TRUE;
  }
  // Flag a link to be altered by hook_translated_menu_link_alter(), but only
  // if it is derived from a menu router item; i.e., do not alter a custom
  // menu link pointing to the same path that has been created by a user.
  if ($item['link_path'] == 'user' && $item['module'] == 'system') {
    $item['options']['alter'] = TRUE;
  }
}

```
> 4 votes

# Answer
I solved the same problem with the Rules module.

Same Question: https://stackoverflow.com/questions/6073793/how-to-redirect-a-user-to-his-account-page-after-login
> 0 votes

---
Tags: 7, users
---


# Question
Title: What are the URLs for devel generated images in CCK fields?
I generated a few nodes with Devel. When I do a `krumo($node)`, the CCK field consisting of an image, does not have a filename. `$field_name['und'][0][filename]` is a string of 0 characters. I only get this: `$field_name['und'][0]['uri'] = public:///garbledImageName.tmp.png`. How do I use this? What function does Drupal use, to convert this public:/// URI into a complete image path? And in the future, can I count on custom created modules to also have the 'uri' value?

# Answer
> 4 votes
Drupal uses the `file_create_url()` function for this:

> Creates a web-accessible URL for a stream to an external or local file.

Code example:

```
$url = file_create_url($field_name['und'][0]['uri']);

```

---
Tags: 7, entities, debugging
---


title: Duplicate Urls for many terms

text:
# Question
Title: Duplicate Urls for many terms
I don’t know why most of my parent terms have duplicate URLs: One like this:

```
     taxonomy/term/1

```

And a second one like this:

```
     taxonomy/term/1/0

```

I have installed Global Redirect and Pathauto, and all urls in the first format are redirected to their alias. However urls in the second format are not. Now google is reporting a large list of duplicate title tags. How can I solve this?

# Answer
There's a setting under the Global Redirect settings to **Remove Trailing Zero Argument**:

According to the description for this option:

> If enabled, any instance of "/0" will be trimmed from the right of the URL. This stops duplicate pages such as "taxonomy/term/1" and "taxonomy/term/1/0" where 0 is the default depth.

That should fix the problem you're having.
> 2 votes

---
Tags: 6, taxonomy-terms, uri
---


# Question
Title: How to show a description when a select box item has been selected
On my "node/add" form I have a "topic" taxonomy term field a user has to select. I would like to be able to display a description about a selected text next to the box, see red box in screenshot:

I'm sure there are CSS/javascript hacks out there, just wondering if there is a "Drupal way" for doing this?

Cheers

# Answer
> 3 votes
This isn't strictly theming, but the following works for me:

Put the following in a custom module:

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

  $items['termdescription/%'] = array(
    'title' => 'Term description callback',
    'page callback' => 'tax_desc_get_description',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function tax_desc_get_description($tid) {

  if (!is_numeric($tid)) {
    return drupal_json_output('Select a term');
  }

  $term = taxonomy_term_load($tid);

  $description = $term->description;

  return drupal_json_output($description);

}

```

This is simply a menu hook that calls a function. You will be calling this menu link to get the description data for the taxonomy term. The second function takes the term ID that will be passed in the ajax call, and gets the term object. From that, it pulls the description set using the standard taxonomy term description.

Next, you'll need to add the following javascript and reference it in your module `.info` file:

```
(function($){
  Drupal.behaviors.taxdescGetDesc = {
    attach: function (context) {

      $(".page-node-add-article #edit-field-tags-und").after('<div id="mycontainer">Select a term</div>');

      $(".page-node-add-article #edit-field-tags #edit-field-tags-und").click(function(){
        $.ajax({
          cache: false,
          type: 'POST',
          url: "/termdescription/" + $(this).val(),
          context: document.body,
          dataType: "json",
          success: function (json){
            $('#mycontainer').html(json)
          }
        })
      })
    }
  }
})(jQuery);

```

You'll probably want to change the ID's and classes that I've used, as I've just used a standard article type for this.

This Javascript will put a div with the ID of `mycontainer` below the select box (this can be styled/positioned with CSS so it matches your image).

when you click the select box, the term description will populate the div created earlier called `mycontainer`.

Just in case, your `.info` file will look like the following:

```
name = taxonomy description
description = taxonomy description from list

core = 7.x

scripts[] = tax_desc.js

```

# Answer
> 1 votes
You may use jQuery the `click()` event. Read more on http://api.jquery.com/click/.

```
jQuery("#idofselectbox").click(function() {
  jQuery("#idofreddiv").html('<h1>Hello All</h1>' + jQuery(this).val());
});

```

---
Tags: theming, taxonomy-terms
---


title: Cron queue not working

text:
# Question
Title: Cron queue not working
I'm trying to set up a cron queue, but for some reason, I don't manage to get this done.

Here is what I have so far:

```
function mymodule_cron() {
    // Setup the queue
    $queue = DrupalQueue::get('import_jobs');
    // Create cache
    drupal_flush_all_caches();
}

function mymodule_cron_queue_info() {
    $queues['import_jobs'] = array(
    'worker callback' => '_import_all_jobs',
    'time' => 15,
    );
    return $queues;
}

```

The `_import_all_jobs` function does it's work excellent, so nothing wrong with that. I use the Ultimate Cron module and my cron job is listed over there:

But for some reason, nothing happens... So I'm wondering what I do wrong...

# Answer
You need to add items to your queue. You have created a queue, but haven't added anything to it, so nothing is being done.

```
$queue->createItem($item);

```

`$item` will get passed to the queue callback function (`_import_all_jobs`).

I would suggest modifying `_import_all_jobs` to import an individual job (`_import_job`). Then `$item` would be a job added to the queue and you let DrupalQueue do its thing.

This article may be helpful: Cron Queues: Processing large amounts of data in cron

And here is some relevant Drupal documentation: Queue operations
> 3 votes

# Answer
If you are not processing multiple items, you could just run `_import_all_jobs` from the cron:

```
function mymodule_cron() {
    _import_all_jobs();

    // Create cache
    drupal_flush_all_caches();
}

```

But it seems like `_import_all_jobs` is doing multiple things and should be modified to work as a DrupalQueue, as I've suggested in my first answer.
> 0 votes

---
Tags: 7, cron, queue
---