# Question
Title: Using Form states in Panel Styles: How to overcome 'outdated' error message
Drupal's FORM API lets you specify Form States. These have a handy visibility state are that let you show/hide parts of a form depending on which fields have been filled in. It's a good way of reducing clutter on a form.

I am building my own custom Panel Style. The style settings has a lot of options, so I want to use the Form Visibility State to hide them.

I have added the code following the tutorials here and here. However, when I select an option on the form, I get this error message:

> The form has become outdated. Copy any unsaved work in the form below and then reload this page.

How can I fix this?

This Dr Drupal tutorial suggests I need to use $form\['form\_build\_id'\], $form\['form\_id'\], $form\['form\_token'\]. However, the tutorial is quite terse, so I'm not sure how to add them to my code.

The code for my panel style is here:

```
<?php
// $Id$

/**
 * Returns form render array.
 */
function coloroptions($form, $form_state)
{
    $form['color_default'] = array(
        '#type' => 'select',
        '#title' => t('Select a Colour'),
        '#options' => array(
            '000000' => t('Black'),
            'ffffff' => t('White'),
            'custom' => t('Custom')
        ),
        '#default_value' => (isset($form['color_default'])) ? $form['color_default'] : '000000',
        '#description' => t('The Colour you want to use')
    );

    $form['color_custom'] = array(
        '#type' => 'textfield',
        '#title' => t('background color for pane'),
        '#states' => array(
            'visible' => array(
                ':input[name="color_default"]' => array(
                    'value' => 'custom'
                )
            )
        ),
        '#default_value' => (isset($form['color_custom'])) ? $form['color_custom'] : '',
        '#description' => t('The Colour you want to use')
    );

    $form['color_location'] = array(
        '#type' => 'select',
        '#title' => t('Box around'),
        '#options' => array(
            'pane' => t('Each pane'),
            'region' => t('Each region')
        ),
        '#default_value' => (isset($form['color_location'])) ? $form['color_location'] : 'pane',
        '#description' => t('Choose whether to include the box around each pane (piece of content) or region (each column or region)')
    );

    return $form;

}

/**
 * @file
 *   Definition of the 'color' panel style.
 */

/* Place this file in themename/plugins/styles/STYLENAME/
/* In theme.INFO add the following:
/* ;----------// Plugin Panels
plugins[panels][layouts] = plugins/layouts
plugins[panels][styles] = plugins/styles
/* Reset your cahce afterwards.  */

$plugin = array(
    'title' => t('Example: Color text style'),
    'description' => t('Simply changes the text color of a pane, as an example.'),

    // Names the function to render a pane. Only required for pane styles.
    'render pane' => 'panels_colors_style_pane',

    // Names the function to render a region. Only required for pane styles.
    'render region' => 'panels_colors_style_region',

    // Names the function providing settings form for the pane. (optional)
    'pane settings form' => 'panels_colors_style_pane_settings',

    // Names the function providing settings form for the region. (optional)
    'settings form' => 'panels_colors_style_region_settings',

    // Provide a template to be used by Pane and/or Region. (optional)
    'hook theme' => array(
        'panels_colors_box' => array(
            'variables' => array(
                'content' => NULL
            ),
            'path' => path_to_theme('plugins/styles/colors'),
            'template' => 'panels-colors-box'
        )
    )

);

/**
 * Settings form for the pane.
 *
 * Any form will do here. The settings will come through to the theme
 * function in $pane->style['settings'].
 * Use form API to construct the form: http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7
 *
 * @param $style_settings
 *   The $style_settings if they've already been set.
 * @return
 *   The form.
 */

function panels_colors_style_pane_settings($style_settings)
{
    return drupal_get_form('coloroptions');

    return $form;
}

/**
 * Settings form for the region.
 *
 * Any form will do here. The settings will come through to the theme
 * function in $pane->style['settings'].
 * Use form API to construct the form: http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7
 *
 * @param $style_settings
 *   The $style_settings if they've already been set.
 * @return
 *   The form.
 */

function panels_colors_style_region_settings($style_settings)
{
    /*    $form['color'] = array(
    '#type' => 'textfield',
    '#title' => t('background color for pane'),
    '#default_value' => (isset($style_settings['color'])) ? $style_settings['color'] : '#000000',
    '#description' => t('Select the background color for the region.')
    );

    $form['color_location'] = array(
    '#type' => 'select',
    '#title' => t('Box around'),
    '#options' => array(
    'pane' => t('Each pane'),
    'region' => t('Each region')
    ),
    '#default_value' => (isset($style_settings['color_location'])) ? $style_settings['color_location'] : 'pane',
    '#description' => t('Choose whether to include the box around each pane (piece of content) or region (each column or region)')
    );*/

    return drupal_get_form('coloroptions');

    return $form;

    dpm($form);

}

/**
 * Render the pane content.
 *
 * The name of this function is referenced in hook_default_panels_styles(), and
 * it's free-form, but of course be careful to namespace it.
 * But the name is just theme_<render pane> where "<render pane>" is what you
 * put into the array above.
 *
 * This is optional, but shows how a plugin can render a pane.
 *
 * Please remember that you have to rebuild the theme registry after
 * introducing this function or changing its name.
 *
 * @param $content
 *   The content of the block to be rendered. It has a title and a content.
 * @param $pane
 * @param $display
 * @return
 *   rendered content
 */
function theme_panels_colors_style_pane($vars)
{
    kpr($vars);
    $display        = $vars['display'];
    $content        = $vars['content'];
    $pane           = $vars['pane'];
    $style_settings = $pane->style['settings'];
    $color          = $style_settings['color'];
    $output         = "";
    if (!empty($content->title)) {
        $output .= "<h3>$content->title</h3>";
    }

    // For this simple example, wrap the content in a div with style.
    // We could have loaded extra css, etc.
    drupal_add_css(drupal_get_path('theme', 'legendary') . '/plugins/styles/colors/yellow.css', 'theme');
    $output .= "<div style='background-color:";
    $output .= $color;
    $output .= ";'>";

    $output .= theme('panels_pane', array(
        'content' => $content,
        'pane' => $pane,
        'display' => $display
    ));
    //   $output = theme('panels_colors_box', array('content' => $output));
    $output .= "</div>";
    return $output;
}

/**
 * The function which will render the panel or region with this style.
 *
 * This is optional, but shows how the plugin can be used to change the
 * rendering of a panel or region.
 *
 * @param $display
 * @param $panel_id
 * @param $panes
 * @param $settings
 * @return
 *   Rendered output for the panel.
 */
function theme_panels_colors_style_region($vars)
{
    $display   = $vars['display'];
    $region_id = $vars['region_id'];
    $panes     = $vars['panes'];
    $settings  = $vars['settings'];
    $output    = '';

    $color_default = $settings['color_default'];
    $color_custom  = $settings['color_custom'];

    if ($color_default != 'custom') {
        $color = $color_default;
    } else {
        $color = $color_custom;
    }

    $output = "<div style='text-decoration: underline; background-color: #$color;'>";

    $where = empty($settings['color_location']) ? 'pane' : $settings['color_location'];

    foreach ($panes as $pane_id => $pane) {
        if ($where == 'pane') {
            // If you are NOT using a tpl.php file (see top of this document), uncomment the following file:
            //    $output .= $pane;

            //If you ARE using a Tpl.php file (see top of this document), uncomment the following file:
            $output .= theme('panels_colors_box', array(
                'content' => $pane
            ));

        }

        else {
            //Loop throught to gather each pane and put them into $allpanes
            $allpanes .= $pane;
            $print_separator = TRUE;
        }

    }

    if ($where == 'region') {
        // If you are NOT using a tpl.php file (see top of this document), uncomment the following file:
        //$output .= $allpanes;

        // If you are using a tpl.php file (see top of this document), uncomment the following file:
        $output .= theme('panels_colors_box', array(
            'content' => $allpanes
        ));
    }

    $output .= "</div>";
    return $output;

}

```

# Answer
I've figured this out!

The form part has to be moved to where `return drupal_get_form('coloroptions');` is.

Then, the visibility options for the Form state have to be updated, so they match the Panel Style form options correctly.

I have posted the code below, as it will make more sense to someone having the same problem:

```
<?php
// $Id$

/**
 * @file
 *   Definition of the 'color' panel style.
 */

/* Place this file in themename/plugins/styles/STYLENAME/
/* In theme.INFO add the following:
/* ;----------// Plugin Panels
plugins[panels][layouts] = plugins/layouts
plugins[panels][styles] = plugins/styles
/* Reset your cahce afterwards.  */

$plugin = array(
    'title' => t('Example: Color text style'),
    'description' => t('Simply changes the text color of a pane, as an example.'),

    // Names the function to render a pane. Only required for pane styles.
    'render pane' => 'panels_colors_style_pane',

    // Names the function to render a region. Only required for pane styles.
    'render region' => 'panels_colors_style_region',

    // Names the function providing settings form for the pane. (optional)
    'pane settings form' => 'panels_colors_style_pane_settings',

    // Names the function providing settings form for the region. (optional)
    'settings form' => 'panels_colors_style_region_settings',

    // Provide a template to be used by Pane and/or Region. (optional)
    'hook theme' => array(
        'panels_colors_box' => array(
            'variables' => array(
                'content' => NULL
            ),
            'path' => path_to_theme('plugins/styles/colors'),
            'template' => 'panels-colors-box'
        )
    )

);

/**
 * Settings form for the pane.
 *
 * Any form will do here. The settings will come through to the theme
 * function in $pane->style['settings'].
 * Use form API to construct the form: http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7
 *
 * @param $style_settings
 *   The $style_settings if they've already been set.
 * @return
 *   The form.
 */

function panels_colors_style_pane_settings($style_settings) {
    $form['color_default'] = array(
        '#type' => 'select',
        '#title' => t('Select a Colour'),
        '#options' => array(
            '000000' => t('Black'),
            'ffffff' => t('White'),
            'custom' => t('custom')
        ),
        '#default_value' => (isset($form['color_default'])) ? $form['color_default'] : '000000',
        '#description' => t('The Colour you want to use')
    );

    $form['color_custom'] = array(
        '#type' => 'textfield',
        '#title' => t('background color for pane'),
        '#states' => array(
            'visible' => array(
                ':input[name="settings[color_default]"]' => array(
                    'value' => t('custom')
                )

            )
        ),
        '#default_value' => (isset($form['color_custom'])) ? $form['color_custom'] : '',
        '#description' => t('The Colour you want to use')
    );

    $form['color_location'] = array(
        '#type' => 'select',
        '#title' => t('Box around'),
        '#options' => array(
            'pane' => t('Each pane'),
            'region' => t('Each region')
        ),
        '#default_value' => (isset($form['color_location'])) ? $form['color_location'] : 'pane',
        '#description' => t('Choose whether to include the box around each pane (piece of content) or region (each column or region)')
    );

    return $form;
}

/**
 * Settings form for the region.
 *
 * Any form will do here. The settings will come through to the theme
 * function in $pane->style['settings'].
 * Use form API to construct the form: http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7
 *
 * @param $style_settings
 *   The $style_settings if they've already been set.
 * @return
 *   The form.
 */

function panels_colors_style_region_settings($style_settings) {
    $form['color_default'] = array(
        '#type' => 'select',
        '#title' => t('Select a Colour'),
        '#options' => array(
            '000000' => t('Black'),
            'ffffff' => t('White'),
            'custom' => t('custom')
        ),
        '#default_value' => (isset($form['color_default'])) ? $form['color_default'] : '000000',
        '#description' => t('The Colour you want to use')
    );

    $form['color_custom'] = array(
        '#type' => 'textfield',
        '#title' => t('background color for pane'),
        '#states' => array(
            'visible' => array(
                ':input[name="settings[color_default]"]' => array(
                    'value' => t('custom')
                )

            )
        ),
        '#default_value' => (isset($form['color_custom'])) ? $form['color_custom'] : '',
        '#description' => t('The Colour you want to use')
    );

    $form['color_location'] = array(
        '#type' => 'select',
        '#title' => t('Box around'),
        '#options' => array(
            'pane' => t('Each pane'),
            'region' => t('Each region')
        ),
        '#default_value' => (isset($form['color_location'])) ? $form['color_location'] : 'pane',
        '#description' => t('Choose whether to include the box around each pane (piece of content) or region (each column or region)')
    );

    return $form;

}

/**
 * Render the pane content.
 *
 * The name of this function is referenced in hook_default_panels_styles(), and
 * it's free-form, but of course be careful to namespace it.
 * But the name is just theme_<render pane> where "<render pane>" is what you
 * put into the array above.
 *
 * This is optional, but shows how a plugin can render a pane.
 *
 * Please remember that you have to rebuild the theme registry after
 * introducing this function or changing its name.
 *
 * @param $content
 *   The content of the block to be rendered. It has a title and a content.
 * @param $pane
 * @param $display
 * @return
 *   rendered content
 // */
function theme_panels_colors_style_pane($vars) {
    //kpr($vars);
    $display  = $vars['display'];
    $content  = $vars['content'];
    $pane     = $vars['pane'];
    $settings = $pane->style['settings'];
    $color    = $style_settings['color'];
    $output   = "";
    if (!empty($content->title)) {
        $output .= "<h3>$content->title</h3>";
    }

    $color_default = $settings['color_default'];
    $color_custom  = $settings['color_custom'];

    if ($color_default != 'custom') {
        $color = $color_default;
    } else {
        $color = $color_custom;
    }

    // For this simple example, wrap the content in a div with style.
    // We could have loaded extra css, etc.
    //    drupal_add_css(drupal_get_path('theme', 'legendary') . '/plugins/styles/colors/yellow.css', 'theme');
    $output .= "<div style='text-decoration: underline; background-color: #$color; overflow:hidden;'>";

    $output .= theme('panels_pane', array(
        'content' => $content,
        'pane' => $pane,
        'display' => $display
    ));
    //   $output = theme('panels_colors_box', array('content' => $output));

    $output .= $color;

    $output .= "</div>";

    return $output;
}

/**
 * The function which will render the panel or region with this style.
 *
 * This is optional, but shows how the plugin can be used to change the
 * rendering of a panel or region.
 *
 * @param $display
 * @param $panel_id
 * @param $panes
 * @param $settings
 * @return
 *   Rendered output for the panel.
 */
function theme_panels_colors_style_region($vars) {
    $display   = $vars['display'];
    $region_id = $vars['region_id'];
    $panes     = $vars['panes'];
    $settings  = $vars['settings'];
    $output    = '';

    $color_default = $settings['color_default'];
    $color_custom  = $settings['color_custom'];

    if ($color_default != 'custom') {
        $color = $color_default;
    } else {
        $color = $color_custom;
    }

    $output = "<div style='text-decoration: underline; background-color: #$color;'>";

    $where = empty($settings['color_location']) ? 'pane' : $settings['color_location'];

    foreach ($panes as $pane_id => $pane) {
        $display->cssregionstyle[] = $color;
        $settings[]           = $color;
        if ($where == 'pane') {
            // If you are NOT using a tpl.php file (see top of this document), uncomment the following file:
            //    $output .= $pane;

            //If you ARE using a Tpl.php file (see top of this document), uncomment the following file:
            $output .= theme('panels_colors_box', array(
                'content' => $pane
            ));
        }

        else {
            //Loop throught to gather each pane and put them into $allpanes
            $allpanes .= $pane;
            $print_separator = TRUE;
        }
    }

    if ($where == 'region') {
        // If you are NOT using a tpl.php file (see top of this document), uncomment the following file:
        $output .= $allpanes;

        // If you are using a tpl.php file (see top of this document), uncomment the following file:
        //  $output .= theme('panels_colors_box', array(
        //    'content' => $allpanes
        // ));

    }

    $output .= "</div>";
    return $output;
}

```
> 0 votes

---
Tags: theming, forms, panels
---


title: Remove folder from basepath of urls?

text:
# Question
Title: Remove folder from basepath of urls?
I have 2 sites locally (in MAMP) both in their own folders. I need both sites to be in the web root which I can change in the MAMP settings each time Im working on a different site.

However now I need to be able to look at both sites 'head to head'. Is there any way (im thinking with the htacess file) to make both sites work at the same time?

# Answer
a bit confused as to what exactly you are asking but i'll answer anyway. also, this question does not seem drupal specific.

yes... you can have both sites in the web root so to speak. however, vhosts will allow you to run both sites from any directory you want. take a look at the apache documentation on vhosts..

if you are doing your development local, you can adjust your hosts file to have sites `dev1` and `dev2` (for example) point back to your local development box (localhost).

as for removing the folder from the basepath, vhosts will handle this for you.

your vhost config might look lke this in httpd.conf

```
<VirtualHost *:80>
 ServerAdmin aasdf@asdfl.net
 DocumentRoot /var/www/html/dev1
 ServerName dev1
 ErrorLog logs/dev1-error_log
 CustomLog logs/dev1-access_log common
</VirtualHost>
<VirtualHost *:80>
 ServerAdmin aasdf@asdfl.net
 DocumentRoot /var/www/html/dev2
 ServerName dev2
 ErrorLog logs/dev2-error_log
 CustomLog logs/dev2-access_log common
</VirtualHost>

```
> 1 votes

---
Tags: uri
---


# Question
Title: Hide fields on the user profile page with preprocess function
On the user profile edit page I can do something like this in my theme's template.php file to hide a field:

```
function MYTHEME_form_user_profile_form_alter(&$form,$form_state,$form_id){
//remove unwanted fields from the form (default value is still saved)
  $form['timezone']['#access'] = FALSE;
}

```

On the profile view page, I am trying to do a similar thing. I want to hide:

```
History
Member for 3 months 4 weeks

```

So I looked up the api function and it's `hook_user_view`

Based on this I try:

```
function MYTHEME_user_view($items) {
$items['member_for']['#access'] = FALSE;
}

```

... however, this does not work after I clear the cache. I'd also like to avoid hiding this using CSS `display:none`.

# Answer
> 5 votes
You do not need to use any preprocess functions tbh :\> its pretty simple Go to `Home » Administration » Configuration » People » Account settings » Manage Display` , History -\> `Format` chose hidden.

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


# Question
Title: How do I add specific CSS classes to each menu anchor?
I have a menu, *user menu*, with several links. (Let's say *A*, *B*, *C*, and *D*.) I want to add classes/IDs for each snchor.

# Answer
> 2 votes
You can do that by using Menu Attributes module.

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.

---
Tags: 7, navigation
---


# Question
Title: How to place a specific comment on top of list
PLease help me with this requirement in D6.

I need to mark one comment as best, so this comment should stick on top of all comments posted irrespective of sort order.

How can this be achieved, any ideas?

# Answer
Found Best Reply module.

> Best reply module allows node authors to mark a particular comment as the best reply. It aims to encourage quality comments and to give some recognition to people posting quality responses.
> 2 votes

---
Tags: comments
---


# Question
Title: Date module not showing Text with Date Popup widget
I have enabled Date Module completely. But when I try to add Date field to my custom content type the widget has only two options "Text Filed" and "Popup Calendar". There is no third option "Text Field with Date Popup Calender"?

# Answer
> 1 votes
I think "Date Popup" module is not enabled. You have to enable it, then it shows the Pop-up calendar option in the select list.

# Answer
> 0 votes
Just choose Popup Calendar, it shows a textbox but when you click with your mouse it shows the popup calendar

---
Tags: datetime
---


title: Formatting text in Drupal 7 not working

text:
# Question
Title: Formatting text in Drupal 7 not working
I am new in Drupal 7 and I am trying to format my text using CKEditor. I started to create a basic page, I supplied the **Title** since it is a required field, then I put my text inside the body, there is a section in the Body that I want to use `<h1>` to make it look like the page title. So to do this, I clicked `Heading 1` from the `Format` drop-down. On my editor the text now looks bigger, but when I tried to save it the `<h1>` tag was not implemented. I also tried to style my text using css but it didn't work.

How can I fix this?

# Answer
> 1 votes
You need to set the text format as **Full HTML**, text format select list will available below the body text area.

If the text format is specified as **Plain text**, then it will remove the html tags.

You can find out more information and best practices here - Specifying the allowed formats for user input

---
Tags: theming
---


title: entityfieldquery execution error

text:
# Question
Title: entityfieldquery execution error
I'm learning entityfieldquery api

I wrote a simple module

```
function demo_menu() {
  $items = array();
  $items['demo'] = array(
    'page callback' => 'demo_list',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

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

  $result = $query->entityCondition('entity_type ', 'node')
    ->execute();

  print_r($result);
}

```

I got this error

```
EntityFieldQueryException: For this query an entity type must be specified. in EntityFieldQuery->propertyQuery() (line 1195 of C:\openserver\domains\drupal7.localhost\includes\entity.inc).

```

I read many articles. This is the most simplest query but it is not working.

# Answer
> 2 votes
Just got the error. remove space from "entity\_type "
from this line
`$result = $query->entityCondition('entity_type ', 'node') ->execute();`

---
Tags: database
---


# Question
Title: How to make a Data Selector a negative value in a rule action?
I create a rule and inside it I added a action, this action involves a data selector: **node:field-labpoints**. I need to make this data selector a negative value.

I tried with `-node:field-labpoints` and `-[node:field-labpoints]` but it is not accepted.

look my capture:

# Answer
You have two ways to do this.

Either you use **PhP filter**, which will add under "data selector" and "add offset" a new option, "php evaluation", which will allow you to post-treat this value. Then you'll just have to set `return intval(- $value);`

Or you can use **whole Rules**, by :

1. Action: **Add a value**, and select your \[node:field-labpoints\]
2. Action: **Calculate a value**, and make it negative
3. In your action, **use this value** instead of the one you selected with the selected.
> 2 votes

---
Tags: rules, actions
---


# Question
Title: Inline CSS stripped from Global: Custom text in Views
I did some research on the problem in the title but haven't found any good solutions yet.

I'm using a Global: Custom text view field in a view and I need inline CSS to work in there.

I know that it gets stripped because security reasons, and I *have to* use inline CSS for my problem. So "use CSS classes" is not a solution, I'm well aware that in most cases that would be the best but it's not ok in this case.

Writing a node.tpl.php for the content instead of using a view in Fields mode is also not possible, becaue I have to use view result counter token on the same div where my inline css should go (with another token inside the inline css).

Thank you!

# Answer
> 1 votes
It's still not wise but use a custom PhP field : Views PhP *(it's "Views custom field if you're on D6)*.

---
Tags: 7, views
---


# Question
Title: How can I generate a list of the numbers of users with Roles B, C, and D that have Role A?
My site has a large number of user roles. To generate a list that shows the number of users with each role, I created a view of users and set a **Contextual Filter** to *User: Roles* and then *Display as Summary*. This gives me a list like this:

* Role A (23)
* Role B (10)
* Role C (15)
* Role D (7)
* Role E (4)

What I would like to do now is to create a new view that shows how many users that have Role A have Role B, C, or D like this:

* Role B (4)
* Role C (6)
* Role D (3)

However, I don't know how to get *Display a summary* to work in this way. If I add **Filter Criteria** such as *User: Role*, then only the count for that role will be shown. However, I want to show the count of users for all roles given that the user has Role A.

Use case: On my site, users get roles based on their interests. They also get roles based on how involved they are on the site (like here on SE). I want to generate statistics on the role choices of my most active users.

# Answer
To do this, I ended up having to make several views, each with a filter of Role = A, etc., as suggested by Praveen S's comment.
> 0 votes

---
Tags: views
---


title: how to add div tag to field collection

text:
# Question
Title: how to add div tag to field collection
I have a field collection named rmr\_bar\_li. I want to add a div to each line item of field collection, that is within field collection. How can I do that? Can any one help?

# Answer
We need to write a `hook_form_alter();`
In my case ,

```
function mymodule_form_alter($form,$form_state,$form_id) {
  form['rmr_bar_li'][und][0]['anyfield']['#suffix'] = <div class = 'class name'></div>;
}

```

Here `anyfield` is field inside the field collection below which you have to place your DIV tag.
> 0 votes

---
Tags: theming, javascript, entities
---


title: login to magento 1.7 from drupal 7

text:
# Question
Title: login to magento 1.7 from drupal 7
```
function custom_user_login($edit, $account) {

  require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
  global $user;

  umask(0);
  Mage::App('default');
  $session = Mage::getSingleton('customer/session', array('name' => 'frontend'));
  try {
    $session->login('alvaro@test.com', 'cec123');

    $session->setCustomerAsLoggedIn($session->getCustomer());
  } catch (Exception $e) {
    print_r($e);
    exit;
  }

```

i am using this set of code from my D7 installation to log-in to magento.But it is not loggin into either D7 or magento.

But when i run this code from a seperate simple php file outside it logs in to magento successfully. what could be the problem.

# Answer
> 0 votes
I used Rules module to set a rule and redirect after that event occurs.

Its not fully error proof. But it works. It logs into both Drupal and Magento

I will update this if i find some errors once i dig deep.

For the time being its fine

# Answer
> 0 votes
The function signature is not right, which may be the reason for the code not executing. See the docs for `hook_user_login` function.

The parameter `$edit` is passed by reference and not directly by value. So, the correct definition your function should be,

```
function custom_user_login(&$edit, $account) {

  // rest of the code goes here (not duplicating).

}

```

Also make sure, your modules name is `custom` and it has files `custom.info` and `custom.module` in the module directory. And offcourse, enable the module ;-)

Also, to suggest you to look into the session and cookie info (based on your comment), you can put an `echo '<pre>';print_r($_COOKIE); echo </pre>` inside your theme's `template.php` file. Or simply install the Devel module, and enter `dpm($_COOKIE);` inside your `template.php`, to see a nicely formatted result. You'll need to clear the cache to again load the fresh template files. Similarly, you can print the `$_SESSION` superglobal to see the session information.

---
Tags: users
---


# Question
Title: Why D7 creates two tables when i add one custom fields in user registration?
I created few custom fields for user registration in Drupal 7.

When I add the "First name" field, two tables are created: field\_data\_field\_first\_name, and field\_revision\_field\_first\_name.

Why are there two tables, if they contain the same data?

# Answer
> 1 votes
You can find the answer on your question on Duplicate data in field\_data\* and field\_revision\* tables. In particular, see this comment:

> The field\_revision tables store the revision id, which never changes in these tables. The field\_data tables store the node's current revision id and does not store old revision data. Basically the field\_data tables only ever contain 1 entry per node. The field\_revisions table will contain the number of revisions you've created, preserving the revision data. So if you never use revisions, then yes, the tables will contain identical data.
>
> Since revisions are a core part of Drupal I don't think there's anything you can do about this. You can probably delete the contents of the field\_revision tables (please test first, don't take my word for it!), but as soon as you start creating/editing nodes the field\_revision tables will repopulate.

---
Tags: entities
---


title: Limit the comments view to node author

text:
# Question
Title: Limit the comments view to node author
Is it possible to add a visibility restriction to article comments? (For instance, only the poster can view comments.)

# Answer
A way by which you can elegantly do this from a custom module would be:

```
/**
 * Implements hook_node_view_alter().
 */
 function my_mod_node_view_alter(&$build) {
   $node = $build['#node'];
   if (isset($build['comments'])) {
     // It is good practice to allow the administrator to see comments of all nodes.
     $build['comments']['#access'] =
       user_access('administer comments') || ($node->uid == $GLOBALS['user']->uid);
   }
 }

```
> 3 votes

# Answer
I can't find contrib module for your task. I suggest you to write some code. In template.php add template\_preprocess\_node()

```
function THEMENAME_preprocess_node(&$variables){
  global $user;
  $variables['some_var'] = ($user->uid == $variables['node']->uid) ? TRUE : FALSE;
}

```

Than in node.tpl.php

`<?php if ($some_var): ?>
 <?php print render($content['comments']); ?>
 <?php else: ?>
 <?php print 'You have no access to see comments'; ?>
 <?php endif; ?>`

Please tell me, if be some problems.
> 2 votes

# Answer
If you are using panels. In the content visability section you can set that up.
> 0 votes

---
Tags: comments
---


# Question
Title: Prevent cron from flushing the cache indiscriminately?
I use Drupal 6 with the Cache Backport module, and all the available cache tables are configured to be stored in Redis (similar to Memcached in function for RAM caching). The caching works very well.

I have noticed that the amount of data stored in Redis gradually grows as the cache warms up, which is expected. However, the amount of stored data regularly drops suddenly to almost nothing.

I ran a test by loading up the cache by running a search for the word "the". Usually the amount of data stored in Redis will climb to between 20 and 40 MB on that query. Then, I ran the filter\_cron job (I use the Ultimate Cron module and can run the different cron jobs selectively.) The Redis memory immediately dropped to almost nothing. After loading up the cache again to 20 - 40 MB, I ran the system\_cron, which instantly resulted in Redis memory dropping even lower than it did on filter\_cron. Both of these results are repeatable every time. So obviously both of the system and the filter cron jobs are indiscriminately flushing the Redis cache, which negates the purpose of a cache.

Can I prevent cron jobs from flushing the Redis cache, and if so, how? Is there not effective intelligent cache expiration logic on an individual key basis? Or would the cache system malfunction if I prevented it from being completely flushed by the cron job?

Thanks a lot for the help!

# Answer
The cache is flushed by the `system_cron()` module, so basically the only way to stop it happening is to hack the core system module (very bad), or use something like Elysia Cron to schedule that particular cron job to run on a slower schedule. One of the module's features is:

> Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.

It's worth bearing in mind that `system_cron()` performs some other tasks as well (cleaning up deleted files, clearing the queue and batch tables, etc.), so using this method will slow down those tasks too.

Although it's a bit long winded, and not very future-proof, perhaps the only way to get to a satisfactory solution would be to implement a cron hook in your own module, which performs the tasks of `system_cron()` minus the cache flush. Then you can schedule the `system_cron()` to run on a slower schedule that suits your caching needs.
> 3 votes

---
Tags: caching, cron
---


# Question
Title: Fast way to get translations of all installed modules
I have a site with a lot of modules. Now I need the german translation (if available) of all this modules.

Is there a faster way than downloading and importing them one by one?

# Answer
> 4 votes
Use the Localization Update module, it will hold all your modules translated and up-to-date.

> Automatically download and update your translations fetching them from localize.drupal.org or any other Localization server.

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


title: Malicious code on my site

text:
# Question
Title: Malicious code on my site
I found that in all the JavaScript files on my Drupal website, there is JavaScript code with an `<iframe>` pointing to an external website. When I open the website through Google Chrome, the browser shows a warning about malware.

How is it possible that someone was able to write code in a JavaScript file?

The file permissions for the settings.php file are 0444.

This is sample of the injected code.

```
jQuery(document).ready(function($) {
  $("#edit-search-web").Watermark(" type the keyword");
});; document.write('<iframe width="55" height="55" style="width:100px;height:100px;position:absolute;left:-100px;top:0;" src="SOMEBADURL"></iframe>');

```

# Answer
> 4 votes
Without knowing the specifics or your installation, nobody can give you the exact reason you got hacked.

I suspect that your server is running a vulnerable version of PHP and that Apache has write access to your site files. Typically, there will be a bot that will GET a specifc URL that will download a script onto the server, which will then append to well-known (or all) Javascript files. These additions will add in the malicious code.

After you fix this problem, you should.

* Patch your PHP to bring it up to the latest revision for your version of PHP.
* Update Drupal to the latest revision for your version.
* Clean out your /tmp folders on the server and reboot it.
* Read up on Securing file permissions and ownership. It is important that you fix permissions each time you update files; a lot of FTP clients botch permissions when they upload.
* If you are on shared hosting, consider moving to a VPS or Drupal specific hosting. Running Apache as your login account makes sense for the server owners, not the website owner.
* Create a git repo in your DOCROOT, add all of the files (the standard gitignore shoud be fine), and create a "remote" repo on the local filesystem that you can `git push` to. This makes backuping up and restoring site files pretty easy.

# Answer
> 2 votes
If the changed files are part of conributed modules, the Hacked! module could comme in handy.

> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.

---
Tags: 7, javascript, security
---


title: Spammers on Drupal 6 site

text:
# Question
Title: Spammers on Drupal 6 site
I think Im getting some spammers adding user accounts to my site. I've been checking the users section of my site daily and I'll see these strange email addresses. So I check on the reports and find that they are spammers. Has anyone encountered this problem? Im currently researching it to try and stop it.

# Answer
> 3 votes
The Spambot module is a great solution for protecting the registration form:

> Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.

I'd definitely recommend it

# Answer
> 3 votes
Yeah, this happens a lot on public sites. I suggest looking into three solutions:

Mollom is a good CAPTCHA based form protector, but it is somewhat unique in that it doesn't always challenge users with the CAPTCHA. It uses some logic to detect the spamminess, and then presents the CAPTCHA on an as-needed basis. This may or may not work well on the user registration form (I am not sure if I have tried it here). It works very well on comment and contact forms.

reCAPTCHA is a module for integrating with the service we all have been used to the last few years.

Honeypot adds a hidden field to a form, and then double checks that the field is empty/unchanged upon submission. Typically, spambots autofill these fields. The end result is that the form protection is transparent to end-users, but does a good job of keeping out the bots. I have had good luck with this approach on user registration forms.

# Answer
> 1 votes
1. Turn on Captcha, it will prevent bots from registering on your site.
2. Enable Email verification, this will prevent users to enter valid email ids.
3. Use contrib modules like spam bot, login tobagan which will automatically delete users who have not verified their accounts within X no of days.

This will save you trouble of verifying accounts manually, once its automated.

# Answer
> 1 votes
Check out the discussion on G.D.O., http://groups.drupal.org/node/77093.

---
Tags: users, advertising
---


# Question
Title: Prevent comments containing html links from beeing validated
Seems very simple and I thought a module for that would be easy to find but no.. I've got a website that's beeing infested by spambots in node comments.

You're probably going to tell to disable full HTML input format, but this doesn't block comments, it just stops the links from linking; but the pollution is still there..

My normal users usually don't post any links. When I say links I mean html links:

```
<a href="http://bloodyspamwebsite.com">Blah</a>

```

So all I want to do is block all comments containing one or more of these html links.

I found blockanonymouslinks but this seems to only work for anonymous users. My spammers are logged-in users.

Any help would be much appreciated. Thanks!

# Answer
Why can't you go for Mollom

> Mollom may block a post outright if it is from a known spammer. If Mollom is unsure how to classify a post, it may require the completion of a CAPTCHA to accept the post. Posts that do not match a "spammy" text pattern and do not originate from known spammers are accepted without the need to complete a CAPTCHA. Essentially, Mollom acts as a proactive content moderator that is on the job 24 hours a day, 7 days a week.
> 0 votes

---
Tags: 7, comments, advertising
---


# Question
Title: Blocks placed in content region appear in wrong positions
Is there something I need to know about the way drupal handles blocks in the content region? I have a very bare bones omega subtheme with a single page promoted to front and two blocks in the content region positioned after the main content 'block' - but they show up before the main content.

# Answer
> 3 votes
I moved the blocks around to different orders and back and they suddenly appeared in the correct positions. Seems that they just needed some fiddling. Please comment if you have a similar experience, I'm interested.

# Answer
> 2 votes
Goto `/admin/appearance/settings/{your_subtheme}`, click on the Debugging tab on the left and then check the *Enable the debugging (placeholder) blocks for the selected roles.* option. This will display the regions and zones for you which will help you figure out the exact positions.

If everything seems to be fine after enabling the debugging settings, then you will need to check out the template files of your sub-theme. Sometimes messing up the page template files can lead to confusions like the one you are having now.

---
Tags: blocks, theming
---


# Question
Title: How to setup custom 404 page that will ignore the path?
I have the pathauto setting up URLs as /Country/Dept/node-name (i.e. - /US/Training/How-To-Create-Node). If I enter a non-existent path at the root, it goes to my default 404 page I created. However, if the path is /Country/Dept/ anything, it just goes to the parent folder. How can I get it to go to the 404 page, regardless of the path?

# Answer
> 1 votes
In my case, the main problem was that there were blank landing pages for the parts of the URL. For instance, there was a blank US page for /US/Training/page-title. So, Drupal was finding /US and just redirected the visitor to that page. Because of this, no 404 was being registered, therefore never redirecting to the 404 page. None of the 404 modules helped for this.

Because I have a Taxonomy term for the Country that is used to set the URL, I simply removed the blank landing pages. Now, it will properly register a 404 and will go to my custom 404 node.

# Answer
> 0 votes
The module 404 Navigation provides a 404 path for a solution for Drupal 7. It doesn't provide any path in the 404 page. You'll just get a message:

> The requested page could not be found.

which is without any path.

Or for more control you can check my answer here.

---
Tags: path-aliases
---


title: Jquery silent error in drupal 7

text:
# Question
Title: Jquery silent error in drupal 7
I'm trying to use an uncotroversial piece of code to change the background color of a div when the mouse hovers over it.

Currently, my install of drupal refuses to register the hover event, I have tried substituting my code with a console.log('hovering') and I still get nothing.

here is the code. http://jsfiddle.net/tmXfW/2/

```
( function($) {
        var msg = $().jquery;
        console.log(msg);
        $('div.quicklink-row').hover(function() {
                $(this).addClass('blue-link');
        }, function() {
                $(this).removeClass('blue-link');

        });
})(jQuery);

```

# Answer
> 1 votes
You should wrap your functionality in a Drupal Behavior. This will make it work even if elements on the page change via ajax and whatnot.

So the following:

```
(function($) {
  Drupal.behaviors.myCustomModule = {
    attach: function() {
      //var msg = $().jquery;
      //console.log(msg);
      $('div.quicklink-row').hover(function() {
        $(this).addClass('blue-link');
      }, function() {
        $(this).removeClass('blue-link');
      });
    }
  };
})(jQuery);

```

But aside from that.... why are you using Javascript for something that can be done so simply with CSS?

```
div.quicklink-row:hover {
  background: #00F;
}

```

# Answer
> 0 votes
The have been several issues with the jsfiddle code.

1. The most suspected line is this: `var msg = $().jquery;` Try changing it to: `var msg = $.fn.jquery;`
2. The jsfiddle has been reported to insert some invisible characters producing the `SyntaxError: Unexpected token ILLEGAL` errors in the console (see this issue)
3. Your code contains only the encapsulation wrapper, but inside it lacks the `$.ready(function(){})` or its equivalent.

So I typed your code from scratch, making the changes (1) and (3) and it worked fine.

---
Tags: 7, javascript
---


# Question
Title: editing how a field is output (changing commas to <br />)
I am getting data from an outside source to populate some of my fields. It comes in as a string separated with commas. In order to display this data in a list format. I did this:

```
$commaString = ($items[0]["#markup"]);
$NoCommaString = str_replace("," , "<br />", $commaString);
$items[0]["#markup"] = $NoCommaString;

```

In field--field-MYFIELD.tpl.php. So now field displays like this:

```
item 1
item 2
item 3

```

instead of

```
item 1, item 2, item 3

```

Which is exactly what I want, yay! However, I'm new to Drupal and am worried I'm bypassing something or not using an API when I should be. So is there a better way to do this?

# Answer
> 1 votes
Just for security purposes I would wrap `$commaString` in `check_plain()` to get rid of any naughty characters or code that could come through.

And as for doing extremely simple things with PHP, you shouldn't have to worry about doing it the "Drupal way" too often. There are such things as PHP wrapper functions which are useful for keeping your code safe from PHP version quirks.

Also just to add, if the question were: "I want to format this CSV as a bulleted list." Then I would've suggested using a `theme()` function like the following:

```
print theme('item_list', array('items' => explode(",", check_plain($commaString))));

```

Because Drupal's theme layer is your friend and will help you to almost never write markup in your code. And I'm not aware of a theme function that converts a CSV string into a newline separated one. Item list is a good example of a theme function, so is a table theme.

---
Tags: entities, theming
---


# Question
Title: Getting nodes related to a taxonomy term selecting from a drop down into another drop down
I have a taxonomy drop down in a content type. Now when I select a particular taxonomy I want to show all nodes related to that taxonomy in another select box.

How can I implement this? If I need to do using Ajax, how can I get all contents after selecting a taxonomy? I am new to Drupal. Is there any module available for this purpose?

Or Please tell me how to get all contents using taxonomy programmatically? I have also to sort via price in a particular content type itself.

I need to do this in Drupal 7.

Thanks

# Answer
Yes, you need to implement this using hook\_form\_alter() and `#ajax`. The following is an example code you could try. The field `field_category` and the table `field_data_field_category` would be your taxonomy field. The `field_nodes` would be your another drop-down where you want to list the selected nodes related to the selected taxonomy.

The example code would sort the nodes by content types. To sort price of each particular content type, you would need to join another table in the query, for example, `field_data_field_price` and add your price field to the order-by clause. HTH.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if( $form_id == 'your_node_form' ){

        $form['field_category']['und']['#ajax'] = array(
            // #ajax has two required keys: callback and wrapper.
            // 'callback' is a function that will be called when this element changes.
            'callback' => '_mymodule_ajax_dropdown_alter',
            // 'wrapper' is the HTML id of the page element that will be replaced.
            'wrapper' => 'replace_field_div',
        );

        $form['field_nodes'] = array(
            '#type'     => 'select',
            '#title'    => t('Nodes'),
            '#options'  => array('' => '- Select -'),
            '#required' => FALSE,
            '#prefix'   => '<div id="replace_field_div">',
            '#suffix'   => '</div>'
        );

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['field_category']) && $form_state['values']['field_category']['und'][0]['tid'] ){
            # when the respective taxonomy is selected, get the nodes related to the selected taxonomy
            $tid = $form_state['values']['field_category']['und'][0]['tid'];

            $query = db_select('node', 'n');
            $query->join('field_data_field_category', 'c', 'n.nid = c.entity_id');
            $query->condition('n.status', 1, '=')
                    ->condition('c.field_category_tid', $tid)
                    ->fields('n', array('nid', 'title'))
                    ->orderBy('n.type', 'ASC');
            $result = $query->execute();
            foreach($result as $row){
                $form['field_nodes']['#options'][$row->nid] = $row->title;
            }
        }else{
            # No taxonomy selected
            $form['field_nodes']['#options'] = array('' => '- Select -');
        }
    }
}

function _mymodule_ajax_dropdown_alter($form, $form_state){
    return $form['field_nodes'];
}

```
> 1 votes

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


title: Content Access module hiding menu links

text:
# Question
Title: Content Access module hiding menu links
I am using Content Access module with Drupal 7. when i restrict node access from a specific role, it also hide link in menu.

is there any way to show restricted links in main menu?

# Answer
I have did this via custom module:

```
function mymodule_form_menu_edit_item_alter(&$form, &$form_state, $form_id) {
     if ($form_state['build_info']['args'][0] == 'edit') {
       $item = $form_state['build_info']['args'][1];

       $form['ignore_access_roles'] = array(
         '#type' => 'checkboxes',
         '#multiple' => TRUE,
         '#title' => t("Ignore access"),
         '#options' => user_roles(),
         '#description' => t("If a user with one of the selected roles has no access to the menu item's path, the menu item is <strong>not</strong> hidden."),
         '#default_value' => empty($item['options']['ignore_access_roles']) ? array() : $item['options']['ignore_access_roles'],
       );

       $form['#validate'][] = 'mymodule_form_menu_edit_item_validate';
     }
   }

   function mymodule_form_menu_edit_item_validate(&$form, &$form_state) {
     if (isset($form_state['values']['ignore_access_roles'])) {
       $form_state['values']['options']['ignore_access_roles'] = $form_state['values']['ignore_access_roles'];

       $form_state['values']['options']['alter'] = TRUE;
     }
   }

   function mymodule_translated_menu_link_alter(&$link, $map) {
     if (!empty($link['options']['ignore_access_roles']) && empty($link['access'])) {

       global $user;

       // Get role ids for which the ignore access option applies.
       $rids = array_values($link['options']['ignore_access_roles']);

       $matching_rids = array_intersect(array_keys($user->roles), $rids);

       if (!empty($matching_rids)) {
         // User has one of the specified roles: override menu link access.
         $link['access'] = TRUE;

         // Localize. This must be done because it is only done for links with
         // access TRUE in _menu_link_translate.
         _menu_item_localize($link, $map, TRUE);
       }
     }
   }

```
> 1 votes

# Answer
The main purpose of the access content system is to have control of what every user can see and avoid every possible security issue. This is the desired behavior and almost every module or general ApI uses it, so you won't find default solutions for this.

I've been in the same situation and the only solution I found was to create a custom modules and, in my case, query directly to the menu table to get all the elements I want, and check the permissions myself to either display a link, or simply a title of the content when the user don't have permissions to see it.
> 1 votes

# Answer
I'm pretty sure you will have to write a custom module to deal with this. Here's my idea: relax Content Access restrictions, i.e. let users view your content. Then your custom module has to implement hook\_node\_load() and output a 403 HTTP response when loading nodes your users should not see. Also hook\_permission() should be implemented, so you will be able to configure access easily at the permission page.

Here's a quick example hiding the entire node and filtering by content type and permission:

```
function mymodule_permission() {
  return array('access reserved content');
}

function mymodule_node_load($nodes, $types) {
  if (in_array('my_reserved_content_type', $types)) {
    if (!user_access('access reserved content')) {
      drupal_access_denied();
    }
  }
}

```

Or you can hide some of the node fields, instead of returning a 403. But this is discouraged according to API documentation for hook\_node\_load()
> 0 votes

# Answer
You can use "Always visible" module.

More detailed answer on your question is here https://drupal.stackexchange.com/a/52149/7313
> 0 votes

---
Tags: 7, routes, users
---


# Question
Title: How can I show only 3 countries in country list (select box)?
I'm using SMS User module which validates users' mobile numbers. There's a select box and all countries in it. Users select country and write their mobile numbers.

I want to show only 3 countries in it, but there's no option in admin panel. I looked up the **sms\_user** table. There is a gateway column and country codes writing. That's all.

How can I modify the country list? When I looked into the module code, I found nothing about countries.

# Answer
I think you are trying to shorten the country select box in user registration form and user edit form. You should not hack the contributed modules. You could create your own module and override the forms using hook\_form\_alter().

I assume you have a custom module and you could implement hook\_form\_alter() to update the country list as you need. Here is the code in mymodule.module tested in my test site:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if( $form_id == 'user_register_form' || $form_id == 'user_profile_form' ){
        $countries = array( // define the countries you want
            93  => 'Afghanistan',
            355 => 'Albania',
            213 => 'Algeria'
        );
        $form['sms_user']['gateway']['country']['#options'] = $countries; // update sms country select box.
    }
}

```

But, to access the field group **sms\_user**, your module must have the heaviest weight, otherwise you won't be able to update `$form['sms_user']['gateway']['country']`.
You can make sure your module is heaviest by creating `yourmodulename.install`.

```
/**
 * Implementation of hook_install()
 */
function mymodule_install(){
    # Fetch max module weight from "system" table.
    $max_weight = db_query("SELECT MAX(weight) FROM {system} WHERE type = 'module'")->fetchField();
    # Make sure this module is the heaviest one in order to run last
    db_update('system')
        ->fields(array('weight' => $max_weight+1))
        ->condition('name', 'mymodule')
        ->execute();
}
/**
 * Implementation of hook_uninstall()
 */
function mymodule_uninstall(){
    db_delete('system')
        ->condition('name', 'mymodule')
        ->execute();
}

```

If you are expert, you can tweak the `weight` field of your module in the `system` table to make it heaviest without creating `yourmodulename.install`, but not recommended. You may need to flush all caches after you implemented this.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Is is it possible to set an expiry time on the cached version of each node individually in a Drupal 6 website?
Is is it possible to set an expiry time on the cached version of each node individually in a Drupal 6 website? The expiry time could be based on any factor.

# Answer
Check out Scheduler.

From the project page:

> This module allows nodes to be published and unpublished on specified dates.

What are some examples of factors for expiry date?
> 1 votes

---
Tags: 6, caching
---


# Question
Title: Is there a limit of tags to associate with content?
I am currently wondering if this is the way to do it and would therefore like some input.

The idea is that I want to show content to specific users. However this can not be done by creating a view with categories because it may not be all in a group that I want to show the content to.

That is why I am thinking of extracting a list of users (where companies have filtered by their request) and implementing them as tags on the content. I will therefore have total control over who's going to see the content.

Does anyone know of any limitations that might hinder this setup? I do not want the tags to show on the content and to be automatic generated from the list. Is this possible?

# Answer
> 0 votes
It's a simple you must follow this 2 Steps :

**First Step** :

1. Create a views that will list your users that you want to reference
2. Add a Reference display to your view make your filters then Save

**Second Step** :

1. Download entity reference module
2. Add new entity reference field "Users that will access this content"
3. Chose the target type : User
4. Choose the mode "Views: Filter by an entity reference view"
5. Select the views that you've build on the first Step (the display type must be Reference and not page or block)

Now you will be able to select the users like a tags on content type but without any access permission

**To restrict the Permission to the referenced user :** download the user reference access module

Then configure it under the user entity reference field settings of your content type

---
Tags: taxonomy-terms
---


# Question
Title: How do I print results after submitting a Drupal form?
I have a simple Drupal Module setup which has a single textbox.

I can return what was typed in the textbox using `drupal_set_message()`:

```
function firstmodule_form1_submit($form, &$form_state) {
    drupal_set_message(t("The user is $username"));
}

```

However `echo $username;` will not work for me, nothing is printed. How can I return results without using `drupal_set_message()`?

# Answer
> 7 votes
The normal way to handle this is to implement a multi-step workflow. See `drupal_rebuild_form()` for more information, but basically you set `$form_state['rebuild'] = TRUE;` in your submit handler, and in the original form function add a check to see if the form's been submitted. If it has, you have access to the submitted values and can manipulate the form as you see fit.

A very basic example:

```
function MYMODULE_some_form($form, &$form_state) {
  // If the form has been submitted, output something related to the submission
  if (!empty($form_state['values']['some_field'])) {
    $form['submission'] = array(
      '#markup' => function_to_get_markup_from_value($form_state['values']['some_field'])
    );
  }
  else {
    // Otherwise build the normal form
    $form['some_field'] = array(
      '#type' => 'textfield',
      // ...
    );
  }

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

```

# Answer
> 2 votes
A form submission handler can only print a message using `drupal_set_message()`, or writing a message in the log with `watchdog()`.

The alternative is saving the necessary data in the session, and redirect the user (using `$form_state['redirect'] = 'page path';`) to a page where the content of the session is shown.

```
function firstmodule_menu() {
  $items['the path for your page'] = array(
    'page callback' => 'firstmodule_show_submitted_data';
    // ...
  );

  return $items;
}

function firstmodule_form1_submit($form, &$form_state) {
  $_SESSION['firstmodule_username'] = $username;
  // ...

  $form_state['redirect'] = 'the path for your page';
}

function firstmodule_show_submitted_data() {
  // Populate $result with the string to show.

  return $result;
}

```

As side note, the first argument of `t()` must be a literal string, not a string obtained concatenating two strings, as in your case. You should use placeholders, as in the following code.

```
drupal_set_message(t("The user is %username", array('%username' => $username)));

```

In Drupal 7, instead of returning a string, you can return a render array.

# Answer
> 1 votes
All submitted data stored in `$form_state`, if u want to see what happens install devel module and after you always can do like this:

Inside your `firstmodule_form1_submit` function to print all the array `$form_state` type - `dpm($form_state)` \- and you will see output, where u can find your textbox username or any other, will be something similar to this `$form_state['values']['username']`

And then you can just print it `drupal_set_message(t($form_state['values']['username']);`

# Answer
> 0 votes
What you need to do is to have a menu callback, basically that would be a page you set up and display the info on.

More info is available here: http://api.drupal.org/api/drupal/includes!menu.inc/group/menu/7 and you need to read more about hook\_menu()

Hope that helps, tell me if you need an example.

---
Tags: forms
---


title: Automated translation of interface

text:
# Question
Title: Automated translation of interface
Long story short: I'm looking for a way to provide translations... the "hard" way. So I don't want to click in the backend to apply new translations or translate it on the "Translate Interface" Page.

I really want to provide it hard coded, and when it's changed, it should get changed in the backend as well.

# Answer
> 0 votes
Since you don't want to use the user interface, the only way to provide a translation of the string used from modules is to set them in the settings.php file.

```
$conf['locale_custom_strings_it'][''] = array(
  'forum' => 'Tavola di discussione',
  '@count min' => '@count minuti',
);

```

Replace "it" with language code for which you want to provide the translation. The array index is the string in English, while the array value is the translated string.

Using this method is pretty *hard*: Each times a new string is translated, the settings.php needs to be edited. There could be also some performance issues, as you are defining a new array row for every new translation; I let you imagine what happens when you have 1000 strings to translate in 5 languages.

When those values are provided, the database is not anymore looked up, as t() contains the following code. (See the first comment.)

```
  // First, check for an array of customized strings. If present, use the array
  // *instead of* database lookups. This is a high performance way to provide a
  // handful of string replacements. See settings.php for examples.
  // Cache the $custom_strings variable to improve performance.
  if (!isset($custom_strings[$options['langcode']])) {
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
  }
  // Custom strings work for English too, even if locale module is disabled.
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
  }
  // Translate with locale module if enabled.
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
    $string = locale($string, $options['context'], $options['langcode']);
  }
  if (empty($args)) {
    return $string;
  }
  else {
    return format_string($string, $args);
  }

```

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


# Question
Title: How do I add rel="nofollow" to links in blocks/menus/etc?
I want to add rel="nofollow" attributes to links that point to login/ToS pages in my Drupal 7 site. How can this be accomplished?

# Answer
> 1 votes
I think this is the module you are looking for:

http://drupal.org/project/menu\_attributes

With Menu Attributes you can set the rel attribute (among many) on the admin section.

---
Tags: navigation
---


# Question
Title: How can I render a field inside a tpl.php that is hidden on the UI
I have a taxonomy field attached to a content type. On the teaser view mode, the field is hidden. I have two sections where I display the content type's teasers. On one section I don't want the terms to show. On the other section, I want them displayed.

I would like to know how I can render this field from the template **node.tpl.php**. It's not available as an element of `$content`, but is attached to the `$node` object.

Thanks

# Answer
You can add any markup or additional fields to the node teaser view or node full view using hook\_node\_view(). The following example is adding a taxonomy name to the teaser view.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'teaser'){
     $tname = db_query('SELECT name FROM {taxonomy_term_data} t WHERE tid = :tid', array(':tid'=>$node->field_category['und'][0]['tid']))->fetchField();
     $node->content['my_taxonomy'] = array(
        '#markup' => '<div>'.$tname.'</div>',
        '#weight' => 10,
      );
    }
}

```

You would not need to update node.tpl.php.
> 0 votes

---
Tags: taxonomy-terms, entities
---


# Question
Title: How to pre-populate fields on a node creation form based on fields from Profile2 module?
There is a content type ("Job Listing") that a business account can use to list job openings, and a Profile2 profile for each business that contains the business's address, organization name and taxonomy terms such as industry type.

95% of the businesses that will list a job posting will use the same information; I could just use the profile information, but I need to account for the 5% that might want to change the job listing form. For example, the job might be in another state or country and that needs to be accounted for. I think the the best way to handle this situation is to have the same fields in both the profile and job listing form but allow the business change the information in the job listing form.

It would make sense to pre-populate the job listing form with business profile information as the default. How do I best do this? I was going to use Rules but I can't find a single option for a Rule before the original node creation form is created.

Should I just use `hook_form_alter()` to access the profile information on orginal node creation and use that information to set the default values?

# Answer
> 7 votes
I created a hook\_form\_FORM\_ID\_alter() function in a helper module that tests to see if the node has a NID and if so if it is not in the operation preview. Then I populate the default values of the form with the companies profile information so they can change it later.

```
// We need to set the default of the Job Listing fields on a new Job Listing form */
function helper_form_job_listing_node_form_alter(&$form, &$form_state) {
  // test if node for has been assigned a NID. If not then populate fields with default data */
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))){
    $profile = profile2_load_by_user ($form['uid']['#value'], 'business_profile');
    // We currently do not know what the profile language is */
    // Organization name
    if (isset($profile->field_job_organization['und'][0]['value'])){
      $form['field_job_organization']['und'][0]['value']['#default_value'] =  $profile->field_job_organization['und'][0]['value'];
    }
    // Set the default address
    if (isset($profile->field_resume_address['und'][0]['thoroughfare'])) {
      $form['field_resume_address']['und'][0]['#address']['thoroughfare'] = $profile->field_resume_address['und'][0]['thoroughfare'];
    }
    if (isset($profile->field_resume_address['und'][0]['locality'])) {
      $form['field_resume_address']['und'][0]['#address']['locality'] = $profile->field_resume_address['und'][0]['locality'];
    }
    if (isset($profile->field_resume_address['und'][0]['administrative_area'])) {
      $form['field_resume_address']['und'][0]['#address']['administrative_area'] = $profile->field_resume_address['und'][0]['administrative_area'];
    }
    if (isset($profile->field_resume_address['und'][0]['country'])) {
      $form['field_resume_address']['und'][0]['#address']['country'] = $profile->field_resume_address['und'][0]['country'];
    }
    if (isset($profile->field_resume_address['und'][0]['premise'])) {
      $form['field_resume_address']['und'][0]['#address']['premise'] = $profile->field_resume_address['und'][0]['premise'];
    }
    if (isset($profile->field_resume_address['und'][0]['postal_code'])) {
      $form['field_resume_address']['und'][0]['#address']['postal_code'] = $profile->field_resume_address['und'][0]['postal_code'];
    }
  }
}

```

# Answer
> 4 votes
I had the same requirement and used the code above to get started. Unfortunately the code above does not take multiple country selections and therefore the dynamic field nature of country specific fields (provinces, states, etc.) into account. I cobbled together a new function to pre-populate the address field but with the ability to switch to the right country.

I got that snippet of code on how to do this from mrfelton who wrote a patch for similar address population functionality for drupal commerce. Thanks for that inspiration.

So here is my function that I used to pre-fill field address data. Please improve on this and give back to the community.

---

```
    //method to prepopulate the address field including switching to the right country context
function field_prepopulate_field_widget_form_alter(&$element, &$form_state, $context) {
    // Forms where the pre-population is supposed to occur
    $validforms = array(
            "job_listing_node_form",
            "job_editing_node_form",
            "some_other_node_form"
    );

    // Check that I am on the right form
    if(in_array($form_state['build_info']['form_id'], $validforms)) {
        // Check that I am changing the right field
        if($context['field']['field_name'] == 'field_address') {
            global $user;
            $user_fields = user_load($user->uid);
            if (isset($user_fields->field_address) && !empty($user_fields->field_address)) {
                // use field_get_items function to avoid the entire language nonsense (tongue-in-cheek) in the array
                $address_data = field_get_items('user', $user_fields, 'field_address');
                //This may look redundant but is important - fill the address fields out once so that the right country is set
                foreach($address_data[0] as $key => $value) {
                    $context['items'][$context['delta']][$key] = $value;
                }
                // regenerate the widget so that the right country specific fields are rendered
                $format = addressfield_field_widget_form($context['form'], $form_state, $context['field'], $context['instance'], $context['langcode'], $context['items'], $context['delta'], array());

                // Switch out the form elements with our newly generated ones.
                foreach ($element as $key => $value) {
                    if (isset($format[$key])) {
                        $element[$key] = $format[$key];
                    }
                }

                // Set the detault values.
                $element['#address'] = $address_data[0];
            }
        }
    }
}

```

---

# Answer
> 1 votes
I made a more generic (but not perfect) module based on the answer from *endless summer*. It assumes that the field names from your profile and the node are the same and will prepopulate all fields from a given profile:

```
function helper_form_job_listing_node_form_alter(&$form, &$form_state)
{
    if (!empty($form['nid']['#value']) || isset($form['#node']->op))
    {
        return;
    }
    $profile = profile2_load_by_user ($form['uid']['#value'], 'business_profile');
    if (isset($profile)) {
        helper_prepopulate($profile, $form);
    }
}

function helper_prepopulate(&$source, &$destination)
{
    foreach($source as $fieldName => $sourceValue)
    {
        if(substr($fieldName, 0, strlen('field_')) !== 'field_' ||
            !isset($destination[$fieldName]['und'][0]) ||
            !isset($sourceValue['und'][0]))
        {
            continue;
        }
        if(isset($destination[$fieldName]['und'][0]['#addressfield']) &&
            $destination[$fieldName]['und'][0]['#addressfield'])
        {
            foreach($sourceValue['und'][0] as $addressFieldName => $addressvalue)
            {
                $destination[$fieldName]['und'][0]['#address'][$addressFieldName] = $addressvalue;
            }
        }
        else if(isset($destination[$fieldName]['und'][0]['#type']) &&
            $destination[$fieldName]['und'][0]['#type'] == 'date_combo')
        {
            $destination[$fieldName]['und'][0]['#default_value']['value'] = $sourceValue['und'][0]['value'];
        }
        else
        {
            $destination[$fieldName]['und'][0]['value']['#default_value'] = $sourceValue['und'][0]['value'];
        }
    }
}

```

---
Tags: rules, users, nodes
---


title: Organic groups joining strategy

text:
# Question
Title: Organic groups joining strategy
Does anyone know how I can force a user to register before being allowed to join an organic group?

Presently, my users receive a link which takes them to a page with a join button. Once they click on the button they are either added to the group as registered members or presented with an "error" message which states they need to register for anonymous users.

I would like to automate the process for those anonymous users.

# Answer
> 0 votes
Try this go on to Configuration \> Organic Groups \>OG Global permissions and Uncheck the fields that u wish to hide from non-members ...

# Answer
> 0 votes
If you want to keep the Join button but not get an "error" (403 page), there are a couple modules out there that will instead giving an error message will bounce the visit directly to the login/register page. Of those Login Toboggan and Redirect403ToLogin are most popular. I'd recommend either - Login Toboggan has more options whereas Redirect 403 To User Login does just this one thing - redirecting from 403 page to login page. If you couple this with enabling the Organic Groups Registration module you'll save users a number of clicks.

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


# Question
Title: Convert Existing Body Fields To CCK Text Fields
Hello i have a Content Type that has been using a body field. Now i was wanting to use a CCK text field instead. Is there a way i can convert existing node body fields for this content type to my new cck field?

Thanks

(drupal 6)

# Answer
> 1 votes
Three options spring to mind:

1. Views Bulk Operations. Safest if the amount of nodes to convert is manageable. You'll probably need to use custom PHP to make the conversion happen though, as the ready-made functionality won't cut your demands.
2. Custom script where you load each node to be converted, modify the structure and run `node_save()`.
3. SQL query, either pure SQL or by custom Drupal (Drush) script. First create your content type, then see the database structure. Then select the body text from the table `node_revisions` and insert it into your field value column for each node.

---
Tags: 6, entities
---


title: Theme specific login redirection?

text:
# Question
Title: Theme specific login redirection?
Anyone know of a way within the theme to redirect to a different url after login?

**Theme #1:** Eg. User goes to `www.examplesite.com` logs in and is taken to `www.examplesite.com/front`

**Theme #2:** Eg. User goes to `www.examplesite.com` logs in and is taken to `subdomain.examplesite.com`

I know of modules that allow us to do this for the entire site but have not found a way to do it just for a single theme.

Background: its for the mobile site UX.

# Answer
> 0 votes
http://drupal.org/project/login\_destination would seem to offer a possibility to use custom PHP snippets as conditions for destinations.

So you need to find out which theme is being used. As I cannot fathom how you are changing your theme in the first place, I cannot help you with that.

---
Tags: 7, redirection, theming
---


# Question
Title: Print translated links in custom page--front.tpl.php
I have a custom template for my front page, where I have to manually set URLs. Some of them are Views paths (such as `news`), some - aliased node URLs (`projects/project-1`). How to get their path translation URL in raw PHP code?

If I say something like:

`<a href="<?php print url('news', array('language'=> $langcode, 'alias' => TRUE)) ?>" ...></a>`

the rendered link is invalid langauge-crossed, such as `mysite.com/es/news`.

I tried also with the l() function but I'm getting untranslated link pointing to the root `mysite.com/news`.

# Answer
This might be an obvious answer to experts, but hopefully this will help some newbie someday. I painstakingly investigated the url stuff in Drupal and my findings surprised me - especially when I referred them to the docs.

In the tpl I placed the following nasty debug lines:

```
<?php dpm(drupal_get_normal_path('alias-en')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'es')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'en')) ?>
<?php dpm(drupal_get_normal_path('en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('/en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('es/alias-es')) ?>
<?php dpm(drupal_get_normal_path('/es/alias-es')) ?>

```

And the results were:

```
alias-en
alias-en
node/298
en/alias-en
/en/alias-en
es/alias-es
/es/alias-es

```

Only the third result `(node/298)` was returned as desired, good for passing to `i18n_get_path_translations`. Even though the `drupal_get_normal_path()` function docs say the language parameter is optional, and subsequently called `drupal_lookup_path()` is said to put current language if NULL is passed, it does not seem to work this way.

`drupal_get_normal_path()` seems to require that you pass two parameters: alias and the language the alias is set for. Only then you'll get the result that will work reliably with `i18n_get_path_translations`.

I'm close to thinking it is a bug in Drupal or docs, and if no one sheds light on me, I'm going to file an issue.
> 1 votes

# Answer
You should use `l` function with `language` options to protect links against language prefix, like this one `mysite/en/node/etc/1` for example:

```
<?php print l(t('title'), $path, array('language' => 'en')); ?>

```
> 0 votes

---
Tags: theming, i18n-l10n
---


# Question
Title: How to implement variable caching of nodes based on published date in a Drupal 6 website?
I have a Drupal 6 website and I want to write a module that will cache nodes based on the published date. Older nodes would be cached longer than newer nodes. I plan to use cache\_set(), cache\_get() and nodeapi hooks to add the node to the cache and check if it is in the cache before loading. However I am not sure if my logic is correct. Can provide any tips to put me on the right track?

# Answer
Boost could do this. Core can not due to the cache\_page bin/table getting cleared on cron & node save. Boost has a cache expiration block that allows for different cache lifetimes.
> 0 votes

---
Tags: 6, caching
---


# Question
Title: Is there any module for importing news from a WordPress site?
When we install Drupal, the first thing we do is importing content from other engines that we used.

Is there any kind of similar converters from other engines, for posts, user accounts, and comments?

# Answer
> 6 votes
For Drupal 7 try WordPress Migrate:

> wordpress\_migrate supports migrating WordPress blog exports (WXR format) into Drupal using the Migrate module. Import of posts, pages, comments, attachments, tags and categories is supported. Imports can be rolled back completely.

and Wordpress Import if you are using Drupal 6:

> This module imports a WordPress blog into Drupal from a WordPress eXtended RSS (WXR) file.

---
Tags: importing-exporting
---


# Question
Title: Drupal Google Translate Module - Must be represented in the url
I have a Wordpress site which I'm planning on porting to Drupal to leverage more advanced functionality.

One plugin I use on the Wordpress site is for Google Translate. Most Wordpress plugins don't represent the language in the url (i.e. they use AJAX or Google Translate direct). I use a decent one which specifies the country code in the URL, and that allows me to use http://petfoodratings.org/ko/, or http://www.petfoodratings.org/de/.

Before undertaking a port to Drupal I want to know if any of the Google Translate Drupal modules do this in the same way?

# Answer
> 1 votes
The only module I know of with a Drupal 7 version is GTranslate.

> GTranslate uses Google power to translate your web page. With 58 available languages your site will be available to more than 98% of internet users.
>
> * Hides "Suggest better translation" pop-up
> * Hides Google top frame after translation
> * Mouse over effect
> * Analytics feature
> * Flags combined in one file to load faster
> * Option to open translated page in new window
> * Available styles Dropdown/Flags/flags with dropdown
> * Valid XHTML
> * Google Translate Element on your site (Google Default translation method)
> * Ability to use SEF URLs and edit translations with Pro version

The module is used from 2250 sites, and 1216 of those are using Drupal 7.

As for the comment written by monymirza, The Google TOS once contained the following paragraph:

> 5.3 You agree not to access (or attempt to access) any of the Services by any means other than through the interface that is provided by Google, unless you have been specifically allowed to do so in a separate agreement with Google. **You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers)** and shall ensure that you comply with the instructions set out in any robots.txt file present on the Services.

The actual version of the Google TOS says:

> Don't misuse our Services. For example, don't interfere with our Services or **try to access them using a method other than the interface and the instructions that we provide**. You may use our Services only as permitted by law, including applicable export and re-export control laws and regulations. We may suspend or stop providing our Services to you if you do not comply with our terms or policies or if we are investigating suspected misconduct.

I am not sure what they mean by *interface*. It could mean you can only access the service through the user interface provided by the browser.

---
Tags: 7
---


title: Slideshow with touchscreen support

text:
# Question
Title: Slideshow with touchscreen support
I'm creating a website and I would to add a slideshow that works also with touchscreen on smartphones and tablets. Could you suggest me some modules that do it?

# Answer
Ok, I've found this: Flex Slider, this seems works on my android smartphone
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: How can I make a fieldgroup visible only to admin users?
I'm using the Field Group module to group fields on my user profile page. I have a number of fields that are only visible to admin users, so I would like to group them together to keep everything organized. I use the Field Permissions module to limit access to the fields to admin users only; however, this module does not restrict permissions for the field groups.

As a result, authenticated non-admin users see an empty fieldgroup. How I deny non-admin users access to a field group that should be shown only to admins?

# Answer
> 3 votes
You are probably using 1.x version of field\_group module (which is the recommended version).

This problem has been solved (for most cases) in this issue. You could try the 2.x-dev version or use a simple JQuery script to remove the empty elements.

---
Tags: users, entities
---


# Question
Title: How can I override the HTML of options on the user edit page so that they do not appear as collapsible fieldsets?
In Drupal 7, several modules on the user edit page provide options in collapsible fieldsets (I think this is the right word-- you can click the title above the option and the area containing the option will "collapse" and fold up).

For example, * timezone (Core) * whether to receive e-mail notifications upon receipt of messages from other members (privatemsg) * disable HTML mail (mimemail)

However, I would prefer to have the titles of these options to be regular titles (i.e., even if you click them, they don't collapse; nothing happens). How can I override this behavior?

I tried the following code based on this question:

```
function mymodule_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['timezone']['#collapsible'] = FALSE;
}

```

However, after clearing my cache, the timezone field is still collapsible on the user edit page.

EDIT: I had accidentally called form\_user\_profile\_form\_alter twice. Consolidating the two overrides fixed my problem.

# Answer
The easier way is to set the #collapsible property to `FALSE`.
As far as I know, when #collapsible is set to `FALSE`, #collapsed is not used anymore, which means the fieldsets are shown as visible; if that is not the case, then set also #collapsed to `FALSE`.

Clearly, this works only for fieldsets; for other form fields, those properties are not used.

As side note, on Drupal 8 collapsible fieldsets are implemented using "details" as form field (at least from the Drupal core code); if you are going to loop through the elements of a form to check for which ones the property should be set, the code should be similar to the following one, for Drupal 8.

```
foreach (element_children($form) as $id) {
  if (!empty($form[$id]) && ($form[$id]['#type'] == 'details' || $form[$id]['#type'] == 'fieldset')) {
    $form[$id]['#collapsible'] = FALSE;
    $form[$id]['#collapsed'] = FALSE;
  }
}

```
> 2 votes

---
Tags: theming
---


title: Autosave with TinyMCE

text:
# Question
Title: Autosave with TinyMCE
I have tried outputting code simliar to the custom\_format example thats included with TinyMCE. I enabled the Autosave module, however I never see a "restore drafts" button. The only setting that doesn't wipe out all the buttons in the editor is using "theme\_advanced\_buttons3". Which also doesn't show a button with the 'restoredraft' value.

Edit: context

# Answer
> 2 votes
I have made some progress on this. I downloaded the TinyAutoSave module from https://code.google.com/p/tinyautosave/ which I believe is more recent than the 'autosave' plugin included with TinyMCE 3.4.4. There may be updates in the latest version of tinymce, but I haven't checked. It seems the codebases have forked, however.

Anyways, I ended up removing autosave from the tinymce.inc file located in sites/all/libraries/wysiwyg/editors. I put tinyautosave/ into sites/all/libraries/tinymce/jscripts/tiny\_mce/plugins.

The solution involved was to not use the 'restoredraft' setting, and use the 'tinyautosave' one instead. I have some strange way that builds the wysiwyg settings table but it basically does:

```
$settings['tinyautosave'] = array('tinyautosave' => 1);

```

# Answer
> 1 votes
After searching a bit I found a fixed issue at drupal.org. A dev describes how it is possible to integrate thirdparty plugins with tinyautosave as an example.

I just did what was described and everything works fine for me now.

---
Tags: wysiwyg
---


title: Table 'main_semaphore' doesn't exist

text:
# Question
Title: Table 'main_semaphore' doesn't exist
I have imported an outdated production Drupal 6.9 site to my development machine. Then, I upgraded all modules to 6.24. After a while, I imported the database of the production site (to have new nodes). The site appears to work properly on the front end. But now it does not update neither form drush, nor by calling update.php from browser. At drush I get:

```
    An error occurred at function : drush_pm_post_pm_update            [error]
    WD php: Table 'mysitedb.semaphore' doesn't exist              [error]
    query: DELETE FROM main_semaphore WHERE value =
    '31092233150575fa189b4d9.09364052' in /path/to/mysite/includes/lock.inc
    on line 224.

```

On Google Chrome, I get just a "Server error" page.

Update: I created semaphore table using this answer but it did not resolve the problem.

# Answer
From main\_ one would think you have a prefix set up on your production site or the development site and perhaps not or werent at the time of upgrade. It's quite confusing what you see, but one thing for sure: compare prefix settings and check MySQL for SHOW TABLES LIKE '%semaphore%' and go from there.
> 3 votes

# Answer
If you have multiple databases in D7 you might need to create a semaphore table in you own DBs:

CREATE TABLE IF NOT EXISTS `semaphore` ( `name` varchar(255) NOT NULL DEFAULT '', `value` varchar(255) NOT NULL DEFAULT '', `expire` double NOT NULL, PRIMARY KEY (`name`), KEY `expire` (`expire`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
> 2 votes

---
Tags: drush, updating
---


# Question
Title: copying actual drupal content to a different drupal site
I know that one can use the export link to copy a content type or a view to another drupal site. But if that content type has a lot of content, is there a way to also copy that over as well?

# Answer
I believe you can do this with the Node Export (export) and Feeds (import) modules.
> 2 votes

# Answer
It may be too late for this, but I needed the same thing and came across this thread so thought others might also. There's a new module called Data Export Import which does exactly what you need:

> The purpose of this module is to be able to export nodes, taxonomy terms and users to data files and then be able to import these data files into Drupal sites. There may be many uses for this module but the main one would be that it can provide a way to export data from a live Drupal site and then to import that live data into an updated version of that site.
> 3 votes

# Answer
I think you're probably looking for the Node export module:

> This module allows users to export nodes and then import it into another Drupal installation, or on the same site.

The Migrate and Feeds modules might also be of interest.
> 2 votes

---
Tags: nodes
---


title: HTML mail template

text:
# Question
Title: HTML mail template
I have created a module that will respond on `hook_node_insert()` and will send the node information to the users subscribed to that node.

What we need to implement is a tpl file that will have the header, body, and footer of the email that will be sent to the users.

I cant call the template file after `hook_node_insert()` because I think that is not the main use of a template file in the first place.

I was thinking to something along these lines.

* The node is inserted
* I call the template file somehow
* I format the mail body for that node
* I return the html in some variable
* I send the returned variable to the mail function

# Answer
As you are using HOOK\_node\_insert() in your module then you can do anything in that function. As the previous answer, its better to use hook\_theme(). So once you call the hook\_node\_insert() you can call a custom function and that will have the return type also that will send the email. Follow the below mentioned steps,

1. Create a new custom function as an example,
```
example_notify_subscribed($node_information)
```

In this function you can send the node informations. So here comes the hook\_theme part.
2. In the hook\_theme() mention a new theme.

```

function your_module_theme($existing, $type, $theme, $path) {
    if($type == 'module') {
        'mail_node_notify' => array(
      'variables' => array(
        'node_information' => NULL,
        'extra_vars' => NULL,
      ),
      'template' => 'notify-mail-subs',
     'path' => drupal_get_path('module', 'your_module').'/template',
      ),
     );
    }
}

```
1. In your example\_notify\_subscribed function call this theme as following,

```

//Send the email
        $email_text_user = theme('mail_node_notify', array(
          'node_information' => $node, //Your node variable information
          'extra_vars' => $extra, //If you send any more information to the template file
          ),
        ));

        $email_values_user = array(
          'module' => 'your_module',
          'key' => 'mail_key', //Unique hook_mail key
          'to' => $send_to,
          'form' => variable_get('site_mail', 'admin@example.com'),
          'subject' => t('Your subject'),
          'body' => $email_text_user,
        );

        $sent_to_user = your_module_mail_send($email_values_user); //Custom Function to send email (HTML)

```

You may need to create some hook\_mail\_alter() and a new class to extend default DefaultMailSystem Class from Drupal. Because Drupal 7 by default sends text emails.

I hope this idea helps.
> 2 votes

# Answer
You can always use a template file in any function: Just define a theme function that uses a template file, and then call the theme function from the hook.

That is what happens with `theme_book_navigation()`, for example. The Book module defines the theme function in book\_theme() (an implementation of hook\_theme()) using the following code.

```
  array(
    'book_navigation' => array(
      'variables' => array('book_link' => NULL),
      'template' => 'book-navigation',
    ),
  )

```

book\_node\_view() (an implementation of hook\_node\_view()) then uses the template file using the following code.

```
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $node->content['book_navigation'] = array(
        '#markup' => theme('book_navigation', array('book_link' => $node->book)),
        '#weight' => 100,
      );
    }
  }

```

The content of `$node->content['book_navigation']['#markup']` is the content of the template file.

What you do with the value returned from theme() is up to you:

* You can save it in a Drupal variable
* You can pass it to a function like drupal\_mail()
* You can store it in a node property you then save in a database table
* You can print it (from a menu callback, for example)

Remember that a theme function using a template file can use preprocess, and process hooks, if you need them.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: a non existing subdomain is added to image urls
I have some images in my home page and from time to time the URL of these images get changed somehow and a subdomain is appended to it automatically.

For example: `www.mysite.com/sites/default/files/image.png` becomes `abc.mysite.com/sites/default/files/image.png`.

Here are some other facts that might have something to do with this issue:

* The site supports two languages (english and arabic which is the default language) and this issue only appears in English Site.
* We had a very old drupal 6 site before that was using Subdomains extensively (using the subdomain module) and I noticed that any subdomain appended to the image url is usually a randomly selected one of these old subdomains. So these domains used to exist. But the weirdest thing is that we actually moved to a completely new server a year ago and we created this new site from scratch using Drupal 7. We have not imported any content or modules from the old site and we don't use subdomains any longer. The old server is no longer active. Also we have removed all subdomains from DNS in cPanel.
* The issue goes away sometimes after clearing the cache.

What could be causing this weird issue?

# Answer
This is rather big guess, but I think you have everything configured so that your virtual host is responding to all subdomains for your primary domain. In Apache terms this would be something like

```
ServerName mysite.com
ServerAlais *.mysite.com

```

And, you have old links that are getting crawled from the old subdomains, and the net result are some bad URLs are being cached.

My suggestion would be to add something like this to your .htaccess

```
RewriteCond %{HTTP_HOST} !www\.mysite\.com [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301,L]

```

Make sure this goes right after the `RewriteEngine on` in the stock Drupal version. I don't think the two example rules in the file will work, as they assume just adding/removing the www and don't take subdomains into account (though I am not 100% sure about this; I haven't looked at these closely in a while). Make sure you clear Drupal cache, too.

Also make sure you back up the file after you change it, so you have the additions the next time you upgrade core.
> 2 votes

---
Tags: media, uri, subsites
---