# Question
Title: Creating a directory for a vocabulary term?
# Background:

I've opened a new vocabulary named "bc" (an acronym for "Blog categories).

# The problem:

Anytime I go to the webpage of each term of this vocabulary, the url is `sitename.com/term`. INSTEAD OF `sitename.com/bc/term`

This is because when I first built the site, I disabled the option (somehow, it was a long time ago) to create folders for vocabularies.

**What I need** is to add a folder only to that vocabulary, i.e a way to make terms of this vocabulary to appear under sitename.com/bc/term.

How can this be achieved?

**Note**: I've already tried to give a pattern, like `bc`, `[bc]`, `[bc]/`. None of these helped.

# Answer
I would bet that you have the module Pathauto enabled. It allows you to create path aliases for mach of your site stuff like nodes and taxonomies. Go to Configuration \> Search and metadata \> URL aliases \> Patterns. That's where you enter the alias patterns for content, taxonomies, etc. Set the default alias to `[term:vocabulary]/[term:name]`

It should be mentioned for any case that the default Drupal path for taxonomy terms is `taxonomy/term/[term:id]`
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Has the Block Cache Settings from Drupal 8 been back-ported to Drupal 7?
I noticed in Drupal 8 there are options to cache a block:

I was wondering if these options exist in Drupal 7 with a module? Has the feature been back ported? or was it a contrib module to begin with?

# Answer
> 0 votes
No, it's impossible to backport. See https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook\_block\_info/7's `DRUPAL_CACHE_CUSTOM` and https://www.drupal.org/developing/api/8/cache/contexts.

---
Tags: 7, blocks, caching, performance
---


# Question
Title: How to load a contributed module load before a custom module?
I have a custom module which is having dependency on contributed module.

How can i make sure that contributed module will be loaded before custom module ?

# Answer
> 2 votes
You could update the module weight so that it is lower than that of the contrib module meaning it would get loaded first.

# Answer
> 1 votes
In your custom modules **.info** file add the following line.

`dependencies[] = contrib-module-name`

For more info refer this.

And add the module\_exists condition in your code.

```
$module = 'required module name';
if(module_exists($module)){
  Your Code;
}

```

Hope this will help you.

# Answer
> 0 votes
If you need to load a specific file or function, you may include the related file using module\_load\_include.

---
Tags: 7
---


# Question
Title: I have a script that need to place after closing tag after of body?
I have JS script . I need place this script after closing tag of body using php. How can i place that script.

# Answer
Adding a `<script>` tag (or any tag except a comment) outside `<head>` or `<body>` is invalid HTML. Drupal doesn't want to help you to produce invalid HTML, so it contains nothing that would help you to do this.

I would examine your motivation for doing this, and reconsider whether you want to produce a valid or invalid document. If you really want to go down the invalid route, then you may as well just edit your theme's html.tpl.php file and stick the script at the bottom, as you won't find any API methods that can be used to do it for you.

FYI, IE10+ will ignore the script altogether, Chrome and FF will honour it for now, but may not in the future, other browsers/versions will probably do various other things.
> 1 votes

# Answer
You can use drupal\_add\_js which has a $scope parameter that you can set to 'footer' or other regions depending on your theme.
> 0 votes

---
Tags: javascript
---


# Question
Title: Any way to add an associated url redirect to a content view?
I want to display the url redirect by which a user entered my site on the commerce orders view so that we can easily see if certain redirects we have set up for direct mails, magazine ads etc have been successful in generating an order. I can't seem to find a way to do this - I'm not a developer so would needs something that can be achieved through the cms.

I know I could do something similar with google analytics/campaigns but I can't use that for this.

Thanks.

# Answer
> 0 votes
Set that variable in the user's `$_SESSION` and then when an order gets created, check to see if that `$_SESSION` variable is there when you save a new order and if it is, write it to `$order->data`.

Alternatively, you can check out Commerce Affiliate which allows you to set up affiliates and provides some extra conditions and actions that you can use. This includes grabbing URL params and storing them on the session.

---
Tags: views, commerce
---


title: Creating node and user with one form

text:
# Question
Title: Creating node and user with one form
I have a content type, 'A'. Now I need a form with the user registration form fields plus the 'A' creation form fields. So when the user (annonymous) submits this form, a user and a node of type 'A' with the filled information would be created.

I have this for now:

```
function my_module_menu() {
  $items['create_node_and_user'] = array(
    'page callback' => 'user_and_node_creation_form',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}

function user_and_node_creation_form() {
  module_load_include('inc', 'node', 'node.pages');
  $output = array();
  $output['user'] = drupal_get_form('user_register_form');
  $output['node_type_a'] = node_add('node_type_a');

  return $output;
}

```

The form is displayed fine, but How can I add a submit handler to manage the node creation after register the user?

# Answer
The Create & Register module does this for you if you don't mind using a contrib module. From the project page...

> This module creates a "lazy registration" which means that the user creates the content first and after this logs in or registers to the site.
>
> **Process**
>
> 1. anonymous user creates a content
> 2. the user will be redirected to the login page (if you set it on the settings form) after he finished the node creation
> 3. the user registers or logs in
> 4. the created node(s) will be assigned to the user after logging in
> 3 votes

# Answer
Using hook\_form\_alter() to modify the original Drupal register form (form id:'user\_register\_form'), so you can change the user register form's fields.

Then just add a submit handler for this form to do something extra, like create a node.

```
$form['actions']['submit'][]='my_own_submit';

```

In your own submit function:

```
function my_own_submit($form, &$form_state){
  //create a node
  $node = new stdClass();
  $node->title = "YOUR TITLE";
  $node->type = "YOUR_NODE_TYPE";
  node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
}

```
> 2 votes

# Answer
There is also Inline Registration which looks promising:

> * Adds user\_register() form to node/add pages if the user is not logged in
> * Associates the new piece of content with the new user
> * Can log the user in after node creation depending on user registration settings
> * Compatible with modules: email\_registration, logintoboggan, registration\_toboggan and other
> 1 votes

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


# Question
Title: $(...).accordion not a function error in drupal7 views accordion module
I had enabled a views accordion for a field in view. On displaying it in a page its not working and I got an error "$(...).accordion is not a function". Can any one help me in solving this?

# Answer
Install the jQuery Update module and set jQuery of your website to `1.7+`.
> 2 votes

# Answer
It seems like your jQuery libraries are creating conflict. Try to use 'jQuery' instead of '$'. Else you can use a simple line of code to avoid jQuery library conflict. https://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page. This link would be helpful.
> 0 votes

# Answer
Exactly what Astha said, example:

```
  <script type="text/javascript">
      jQuery.noConflict();
          jQuery(function(){
              var H = jQuery(".owl-item").height();
              jQuery(".plate").height(H);
          });
  </script>

```

Every `jQuery` used to be a `$`.
> 0 votes

---
Tags: views, navigation
---


# Question
Title: What is the relationship between field_data_field_ and field_revision_ tables?
It seems that the field\_data\_field\_ and field\_revision\_field\_ tables contain exactly the same columns and data, except the revision table contains a row for every revision whilst the data table only contains a copy of the latest revision.

What is the point of having the 2 tables ? Which table is accessed when a node is loaded ?

# Answer
> 0 votes
> **{field\_data\_\[field\_name\]}**
>
> Standard data storage for a field. It's recommended you use \_field\_sql\_storage\_tablename to get the name of this table.
>
> **{field\_revision\_\[field\_name\]}**
>
> Standard revision storage for a field. It is recommended to use \_field\_sql\_storage\_revision\_tablename to get the name of this table.

For more details

# Answer
> 0 votes
The revision table is to track changes and what they are. So the current content is still a change.

E.g if you wanted to revert back to an older version what would drupal do with the current version if it wasn't already in the revision table? It would have to then write it to the revision table so this now "old" remains tracked. What date would it give the newly added revision? It would also have to store somewhere else who was the author of that original change thats now no longer the latest

Cleaner and simplier to put any change directly into the revision table.

Also revisioning is optional so you couldn't say get rid of the data table and run everything from the revision table. You also wouldn't always want to read the revision table as there's alot of extra rows in there that are unnecessary

---
Tags: nodes
---


# Question
Title: How to avoid admin account to be blocked for all ip's by failed attemps to login?
In my drupal site, often i see this message for the admin account

```
Sorry, too many failed login attempts from your IP address. This IP address is temporarily blocked.

```

I know i can solve it clearing the 'flood' database table, and i'm almost sure it is caused by people or bot trying to login as admin. 'Almost' for in the table flood the failed attemps have identifier '1-127.0.0.1' that is the local ip and it sound strange to me... There is a way to avoid the problem for good? (and to be sure it is about people/bot trying to login and not something else?)

(I mean obviously a convenient way. Allowing all the login attemps without blocking them is not a solution.)

# Answer
> 6 votes
The answer can be found in this article

```
https://www.karelbemelmans.be/2015/04/reverse-proxy-configuration-for-drupal-7-sites/

```

Adding these lines to settings.php solves the issue:

```
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');
$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';

```

Added these lines, in the flood table of the drupal site database, every failed login request is logged with the real ip the request came from.

The real problem, indeed, was not lying in the failed login attemps, but in linking all the attemps to the loopback address. Looking at the flood table in drupal database, I could see every request under the ip 127.0.0.1, which is wrong and causes any request from any user (and any ip) to be blocked if anyone from any ip tried to login with wrong passwords. Linking attemps to their right ip makes the drupal flood protection working as expected, that is blocking attemps only from the ip which tried to login with wrong password.

---
Tags: 7, users
---


title: 404s on all pages except homepage

text:
# Question
Title: 404s on all pages except homepage
I have copied a Drupal installation onto my local machine and I am now running into an issue where only the homepage will load and all other links return a 404.

Clean URLS are enabled but even attempting to manually type the URL like:

```
?q=admin/module

```

fails...

I have tried the following:

* Setting AllowOverride to All
* including the mod\_rewrite module
* including the usr\_module
* setting the baseURL in settings.php

None have yet appeared to have any effect.

Can anybody suggest anything else to try?

# Answer
Check that you have the .htaccess file present in your Drupal root folder.
> 2 votes

# Answer
This happened to me once, I copied an entire site folder and clean urls didn't work. I'd copied my files by just selecting all the files in a folder, which doesn't select hidden files, so I was missing my .htaccess file in the drupal root folder.
> 1 votes

# Answer
This problem could also be caused by editing your Apache config file and changing the default value of DocumentRoot "/var/www/html". Try keeping it at the default even if your site's files are not located in /var/www/html.
> 0 votes

---
Tags: 7, uri
---


# Question
Title: Check db_merge status whether inserted or updated
I am using `db_merge()` in my code, and I would like to print a status message with `drupal_set_message()` that reports if the record has been added or updated.

Is it possible?

# Answer
> 2 votes
`MergeQuery::execute()` returns `MergeQuery::STATUS_INSERT` when the data was inserted in the database table, and `MergeQuery::STATUS_UPDATE` when a row was updated.

`MergeQuery` is the class of the object returned from `db_merge()`.

```
public function execute() {
  if (!count($this->condition)) {
    throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  }
  $select = $this->connection->select($this->conditionTable)
    ->condition($this->condition);
  $select->addExpression('1');
  if (!$select->execute()->fetchField()) {
    try {
      $insert = $this->connection->insert($this->table)->fields($this->insertFields);
      if ($this->defaultFields) {
        $insert->useDefaults($this->defaultFields);
      }
      $insert->execute();
      return self::STATUS_INSERT;
    }
    catch (Exception $e) {
      // The insert query failed, maybe it's because a racing insert query
      // beat us in inserting the same row. Retry the select query, if it
      // returns a row, ignore the error and continue with the update
      // query below.
      if (!$select->execute()->fetchField()) {
        throw $e;
      }
    }
  }
  if ($this->needsUpdate) {
    $update = $this->connection->update($this->table)
      ->fields($this->updateFields)
      ->condition($this->condition);
    if ($this->expressionFields) {
      foreach ($this->expressionFields as $field => $data) {
        $update->expression($field, $data['expression'], $data['arguments']);
      }
    }
    $update->execute();
    return self::STATUS_UPDATE;
  }
}

```

---
Tags: 7, database
---


# Question
Title: How to change block visibility/pages in hook_block in my module?
I implement mymodule\_block and for case 'list' I have blocks like:

```
  $blocks[CN_BLOCK_RHM_BUTTONS] = array(
        'info' => t("Block name"),
        'status' => 1, // on by default
        'weight' => -99, // should be at the top
        'region' => 'right', // RHM
        'visibility' => 1, // Only on these pages
        'pages' => 'page1' . PHP_EOL .
          'page2' . PHP_EOL .
          'page3' . PHP_EOL

```

This works great for new blocks created on our dev site. But I want to change the pages settings in source control, and for these changes to propagate when we updated this module on our production site. It seems that for existing module deltas, Drupal looks at the `block` table fields and ignores any changes in `hook_block`. If these any feature of Drupal or cool snippet that will help me 'reset' blocks to the module's settings?

# Answer
> 1 votes
You can achieve this by writing a hook\_update in your module's .install file. You will need to update the 'block' table directly in that hook to change the block settings as needed. After moving your updates to production, run update.php, which will apply the changes in hook\_update.

---
Tags: 6, blocks
---


# Question
Title: Fetch column sum from database and print the output using static/dynamic queries
I want to get the sum of the values in a column I ten print. I am executing the PHP code in the /devel/php page from the Devel module.

The query I want to execute is `SELECT SUM(column_name) FROM table_name`.

I tried the following code, but I get a *Call to undefined function db\_result()* error.

```
$val = db_result(db_query('SELECT SUM(column_name) FROM {table_name}'));
print $val;

```

I also tried the following code, but I get a *Object of class DatabaseStatementBase could not be converted to string in eval()* error.

```
$query = db_select('table_name');
$query->addExpression('sum(column_name)', 'total');
$result = $query->execute();
print $result;

```

If I do not print `$result`, it works and executes, but I want to print the value.

How can I achieve this?

# Answer
> 0 votes
The first error is caused from the fact that Drupal 7 doesn't define `db_result()` anymore; it was used from Drupal 6.

The second error is caused from `$query->execute()` that returns a `DatabaseStatementBase` object, which cannot be convert to a string. (Converting the object to a string is what PHP does when an object is passed to `print`.)

You should use code similar to the following.

```
$query = db_select('table_name');
$query->addExpression('SUM(column_name)', 'total');
$result = $query->execute()->fetchField();

```

---
Tags: 7, database
---


title: Pass URL to menu item call back

text:
# Question
Title: Pass URL to menu item call back
I'm implementing `hook_menu` to add a new tab to the user account page. I'd like to pass a URL as the page callback (a local URL for an existing page on the site). the `page_callback` parameters just accepts a function name. **How would I go about using that to pass a URL?**

# Answer
You can use `page arguments`:

```
function MYMODULE_menu() {
  $items['foo'] = array(
    'title' => 'Bar',
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_baz',
    'page arguments' => array('http://google.com', 'another arg'),
  );

  return $items;
}

function MYMODULE_baz($url, $another_arg) {
  // Do something with $url, e.g. redirect.
  drupal_goto($url);
}

```

That's quite a contrived example, if you *are* redirecting, you could shorten that by just using `drupal_goto` as the callback:

```
function MYMODULE_menu() {
  $items['foo'] = array(
    'title' => 'Bar',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('http://google.com'),
  );

  return $items;
}

```
> 1 votes

---
Tags: routes
---


title: "Revert to last revision" action

text:
# Question
Title: "Revert to last revision" action
I made an update to a site for global search and replace of text across nodes and was too far-reaching. For a specific content type I need to revert my Node update of ~500 nodes.

I found this solution in the VBO issue queue: https://www.drupal.org/node/1166630

But in evaluating this code a new revision is made by it is *not* set as the `current revision` of the node. If I visit the node revisions page and invoke `node_revision_revert_confirm_submit` a new `current_revision` is set for the node.

Code I'm trying:

```
/**
 * Implementation of hook_action_info().
 */
/**
 * Implements hook_action_info().
 */
function revert_last_revision_action_info() {
  $action = array(
    'REVERT_LAST_REVISION' => array(
      'label'        => t('Revert to Last Revision'),
      'type'         => 'node',
      'configurable' => FALSE,
      'triggers'     => array('any'),
    ),
  );
  return $action;
}

/**
 * Action function for REVERT_LAST_REVISION.
 */
function REVERT_LAST_REVISION(&$entity, $context = array()) {
  $node = $entity;
  $revision_list = node_revision_list($node);
  unset($revision_list[$node->vid]);
  if (count($revision_list) > 0) {
    $last_revision = max(array_keys($revision_list));
    $node_last_revision = node_load($node->nid, $last_revision);
    $node_last_revision->revision = TRUE;
    $node_last_revision->log = "Reverted via bulk operation action."; // Log message
    dpm($node_last_revision, __FUNCTION__);
    node_save($node_last_revision);
  }
}

```

Using devel the `$node` arrays look the same so I'm confused as to why my revert revision code snippet is not making the new revision the `current_revision`. The only thing `node_revision_revert_confirm_submit` is doing is setting `$node->revision = TRUE` and calling `node_save()`.

Anyone have any ideas?

**EDIT: 11/16/2015**

As others have mentioned perhaps this has to do with how VBO is initiating the action.

I've also tried the below code but the Node isn't saved.

```
/**
 * Implements hook_action_info().
 */
function revert_last_revision_action_info() {
  $action = array(
    'REVERT_LAST_REVISION' => array(
      'label'        => t('Revert to Last Revision'),
      'type'         => 'node',
      'configurable' => FALSE,
      'triggers'     => array('any'),
      'behavior'     => array('changes_property'),
      'vbo_configurable' => FALSE,
      'pass rows'        => TRUE,
    ),
  );
  return $action;
}

/**
 * Action function for REVERT_LAST_REVISION.
 */
function REVERT_LAST_REVISION(&$entity, $context = array()) {
  $revision_list = node_revision_list($entity);
  unset($revision_list[$entity->vid]);
  if (count($revision_list) > 0) {
    $last_revision = max(array_keys($revision_list));
    $entity = node_load($entity->nid, $last_revision, TRUE);
    $entity->revision = TRUE;
    $entity->log = "Reverted via bulk operation action.";
  }
}

```

# Answer
After much debugging this appears to work. This code appears to revert to the most recent revision properly and does not cause a 2nd node save to occur:

```
/**
 * Implements hook_action_info().
 */
function revert_last_revision_action_info() {
  $action = array(
    'REVERT_LAST_REVISION' => array(
      'label'        => t('Revert to Last Revision'),
      'type'         => 'node',
      'configurable' => FALSE,
      'triggers'     => array('any'),
      'behavior'     => array('view_property'),
    ),
  );
  return $action;
}

/**
 * Action function for REVERT_LAST_REVISION.
 */
function REVERT_LAST_REVISION(&$entity, $context = array()) {
  $revision_list = node_revision_list($entity);
  unset($revision_list[$entity->vid]);
  if (count($revision_list) > 0) {
    $last_revision = max(array_keys($revision_list));
    $entity = entity_revision_load('node', $last_revision);
    $entity->revision = TRUE;
    $entity->log = "Reverted via bulk operation action.";
    entity_save('node', $entity);
  }
}

```

Does anyone know what is causing the final node save in ViewsBulkOperationsAction::execute to not fire? I can't tell if it's because of the action info behaviors not set as: `save`, `pre-save`, or `changes_property` values. Or perhaps it's the usage of `entity_save` here instead of a `node_save` ...

I've debugged this with a few nodes using Batch and single nodes.
> 5 votes

# Answer
The difference is that the node is saved twice: Once in the custom action and once from the the Views Bulk Operations action. Because the `$entity` object hasn't been changed, `entity_save()` saves the previous version of the node, thus setting the node back to previous revision instead of the newly created one.
> 2 votes

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


# Question
Title: Webform token for select field value (not key)
I have a webform select field called `tour` and I have set up an email to go out, using the default template:

```
Submitted on [submission:date:long]
Submitted by user: [submission:user]
Submitted values are:
[submission:values]

The results of this submission may be viewed at:
[submission:url]

```

When the email goes out, it sends the `key` (nid):

```
Tour: 8349

```

rather than the `value` of the option:

```
Tour: 10-Jan-16 - Awesome Tour

```

I have tried the following tokens:

```
[submission:values:tour:label]
[submission:values:tour:value]
[submission:values:tour:withLabel]

```

I am looking for the proper token to output the value in the key/value pair of a select field.

For the `tour` field, I am replacing the options via a hook. I only mention this step for completeness sake as I don't think it has any impact on my issue.

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {

    // get all tours
    $query = db_select('node', 'n');
    $query->fields('n', array('nid', 'title'));
    $query->condition('n.type', 'tour');
    $query->join('field_data_field_tour_type', 't', 't.entity_id = n.nid');
    $query->fields('t', array('field_tour_type_value'));
    $result = $query->execute();

    // group by tour type
    $options = array();
    while ($row = $result->fetchObject()) {

      // tour type 1
      if ($row->field_tour_type_value == 1) {
        $options['Type 1'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
      }

      // tour type 2
      else if ($row->field_tour_type_value == 2) {
        $options['Type 2'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
      }
    }

    ksort($options);

    // set the tour options correctly
    $form['submitted']['tour']['#options'] = $options;
  }
}

```

# Answer
> 0 votes
It turns out the issue was with the form alter hook. I had updated the `#options` which made the form work just fine, however I needed to update the webform component with a line delimited list of key|value pairs.

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {

    // get all tours
    $query = db_select('node', 'n');
    $query->fields('n', array('nid', 'title'));
    $query->condition('n.type', 'tour');
    $query->join('field_data_field_tour_type', 't', 't.entity_id = n.nid');
    $query->fields('t', array('field_tour_type_value'));
    $result = $query->execute();

    // group by tour type
    $options = array();
    $flat_options = array();
    while ($row = $result->fetchObject()) {

      // tour type 1
      if ($row->field_tour_type_value == 1) {
        $options['Type 1'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
        $flat_options .= $row->nid . '|' . date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title . "\n";
      }

      // tour type 2
      else if ($row->field_tour_type_value == 2) {
        $options['Type 2'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
        $flat_options .= $row->nid . '|' . date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title . "\n";
      }
    }

    ksort($options);

    // set the tour options correctly
    $form['submitted']['tour']['#options'] = $options;
    $form['#node']->webform['components'][7]['extra']['items'] = $flat_options;
  }
}

```

I've added the `$flat_options` variables to handle this and assigned it to the proper field in my form array. Keep in mind referencing the component by number `[7]` is not the cleanest and most maintainable way to do this but it works in a pinch.

---
Tags: 7, webforms, tokens
---


title: Mini Calendar As Views Exposed Filter

text:
# Question
Title: Mini Calendar As Views Exposed Filter
I would like to have a calendar be displayed as a filter for a view. When a user clicks on a date on the calendar the views result on **this** page are updated (preferably via Ajax) to show the chosen dates event. Such as the design below. **The calendar should not be a popup calendar.**

I am aware of the date popup calendar in views exposed filter options but that only displays the calendar as a popup calendar as expected.

I have tried to look into the calendar module as well, however the default behavior of the mini calendar block does not fit my needs as when the user clicks on a date on the mini calendar it will redirect the user to that specific dates calendar page instead of updating the views listing.

Any suggestions or direction on how to implement such a feature would be greatly appreciated!

# Answer
> 1 votes
You can achieve this with **calendar** module and **Date API**. The default mini calendar is redirecting to a new page, but you can override it in your template file. I would suggest to use ajax link api module to load your content in a div you would like. You can do something like the following

```
/**
 * Alters link url in calendar events block in order to filter events at /events
 *
 * @see template_preprocess_calendar_datebox()
 */
function <themeName>_preprocess_calendar_datebox(&$vars) {
  $date = $vars['date'];
  $view = $vars['view'];
  $day_path = calendar_granularity_path($view, 'day');

 //$vars['url'] = 'exhibitions/calendar/' . $date;
  $vars['link'] = !empty($day_path) ? l_ajax($vars['day'], $vars['url'], '#block-system-main') : $vars['day'];
}

```

l\_ajax function is used to load contents via ajax. Let me know if you need any help.

---
Tags: datetime, views
---


# Question
Title: How to use entity reference field titles in Views exposed and combined filters
I have two content types: Institution and Contact.

Any number of Contacts are associated with any number of Institutions.

Contacts are associated with Institutions via an Entity Reference field.

I have a view defined as follows:

Format: Show: Fields Content: Published (Yes) Content: Type = (Institution) Content: Title (exposed) Content: Contact (exposed) Combined: Titles and Contacts (exposed)

The current sticking point is the exposed filter for Contact (an Entity Reference) requires the integer value of field\_data\_field\_contact.field\_contact\_target\_id, which frontend users have no means of knowing. I need a way of translating a Contact node's Title to the target ID transparently, and this method must also be accessible to the combined field Titles and Contacts.

Result sets for contacts are in the thousands, so providing a dropdown to the view is not workable.

The view type is likely set in stone, because it has been in production for years and has a great many fields.

# Answer
> 0 votes
You just need use Views Reference Filter module

---
Tags: views, entities
---


title: Domain and URL variables

text:
# Question
Title: Domain and URL variables
I have inherited some bad code in a Drupal 7.x site and it needs to be cleaned up. Several places in the code the URL is hard-coded and I want to change that. For example, in many of my javascript (.js) files I have something like this:

```
var url= 'http://dev3.ws.mysite.com/index.php/api/alerts_mix/x-api-key/blahhhhhhhhhzBkfqPTq4SWuCiLONePNfschNft';

```

In the PHP code I have the following:

```
     $url="http://dev3.ws.mysite.com/api/checkin/x-api-key/blahhhhhhhhhuRCMIWM0Nw0rM2cDK7tTJTPW?uid=11&lt="

```

First question...is it OK to have the entire URL for the API (including the key) hard-coded or should we be calling this some other way?

Second...for both the js and PHP, what can I use in place of the HTTP and domain (http://dev3.ws.mysite.com) so it is a variable and gets those values from the config files so I don't need to change this every time when making a new dev site?

# Answer
I suggest you add it in your custom module in hook\_init then it will exist everywhere,

```
function yourmodule_init(){
     $url="http://dev3.ws.mysite.com/api/checkin/x-api-key/blahhhhhhhhhuRCMIWM0Nw0rM2cDK7tTJTPW?uid=11&lt="
    drupal_add_js(array('yourmodule' => array('myurl' => $url)), array('type' => 'setting'));
    variable_set('myurl',$url);

}

```

Then in modules you can get it with

```
$url=variable_get('myurl');

```

and in JS files

```
var url=Drupal.settings.yourmodule.myurl;

```
> 0 votes

# Answer
For configuration, like an API server URL, I'd suggest using Drupal variables. There are several ways to set the variable:

1. In the settings.php:

`$conf['api_server'] = 'http://example.com';`

2. With Drush:

`drush vset api_server 'http://example.com'`

3. Build an admin screen where you can set the value. (Probably overkill in this case.)

In your code where you need the URL, use variable\_get():

```
$url = variable_get('api_server');

```

To access the value in JavaScript see: How to pass PHP variables to Javascript/jQuery?
> 0 votes

---
Tags: javascript
---


title: time-based temporary authentication

text:
# Question
Title: time-based temporary authentication
Is anyone aware of a time-based rather than one-time login authentication module for Drupal?

We've discovered a problem where some email servers with advanced security tools will crawl through emails to verify the links in them. In so doing -- they invalidate the one-time login links, preventing some users from using them. Rather than verify on whether the link was clicked once, I want to invalidate it based on time. For example -- the link to login is valid for 1 hr from when it was generated.

# Answer
In Drupal 7 you can do something like the following:

Set `user_password_reset_timeout` variable (i.e. in settings.php i.e. in settings.php:

```
$conf['user_password_reset_timeout'] = '600000';

```

Then it will use this time after password generation link, when this much time elapsed the link will be invalidated.

You can follow the thread here
> 0 votes

---
Tags: users
---


# Question
Title: How to redirect users to log in page when they try to access the order page, but not when they try to check out
I'm using Checkout Login module that adds an inline login form to the account information checkout pane. No anonymous users have to activate their accounts to complete checkout or payment, which is all I want. However, after the PayPal redirects users back to my site, and users try to access the order (order history) page, the following message appears:

> You are not authorized to access this page.

Is there a way I can re-direct users to login page when they try to access the order page, rather than the above message appearing?

In short, I want my users to be redirected to login page when they try to access order (order history) page, but not when they try to checkout.

# Answer
That's one of the main features of the LoginToboggan module.

When the *Present login form on access denied (403)* is enabled in its setting form, any access denied page will display a login page. Upon login, users are redirected back to the previously requested path.
> 3 votes

# Answer
Yes, You can handle it with `Rules`, create a rule in `admin/config/workflow/rules/reaction/add` and in `react on event` select `commerce order is view` (or completing the checkout process) then add condition that `if user not logged in` on action `Redirect` user to login page.
> 1 votes

---
Tags: commerce, users
---


# Question
Title: How to print only certain block of content in a view
I have a view that displays shipping details that you print and put on a box before shipping. But using Print module when you click the link it gives entire page to print with all the headers, footers and menus. I need only that block of text rendered by a view.

Also I couldn't make the Print module link appear in a view even though it claims it works, so I had to use View Footer Area and add some PHP to make link work.

```
<?php $current_url = getenv('REQUEST_URI'); ?>
<img src='/sites/all/modules/print/icons/print_icon.png'>
<a href='/print<?php print $current_url; ?>'>Print</a>

```

But like I said it prints entire page and I need only view content.

# Answer
I would look at this as most a front-end styling problem. Basically, you need to add print-only style rules that hide all the page elements you don't need. You can do this via an inline media query:

```
<style>
@media print {
  /* @TODO: Add other selectors that remove page elements
  header, footer, .my-custom-class, #my-custom-id {
    display: none;
  }
}
</style>

```

Or a better, more portable, method is to just attach a custom print CSS stylesheet to whatever view that needs to be altered for printing:

```
drupal_add_css(drupal_get_path('theme', 'MYTHEME').'/css/print-page.css', array('media' => 'print'));

```
> 1 votes

# Answer
In addition to Shawn Conn's solution which is perfectly fine, you can add a separate `page.tpl.php` based on your path. You can define it your `page preprocess` function in `template.php`. Then in your tpl, display only page content. no other regions like header and footer etc.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to filter views block by content type
1. I added two content types for views slideshows.
2. I added slides to both content types.
3. I created a views slideshow block using one content type.
4. I cloned the above view \> Now, I have two views slideshow blocks.

Now, both blocks are linked. Updating one setting updating the other. How can I do the settings so views block1 filtered by content type1 and views block 2 filtered by content type2?

# Answer
> 1 votes
Add a filter of content:type in one of your display Also, You can select this block override at the top when you do any specific block related changes. check the screenshot https://i.stack.imgur.com/JIIx4.png

---
Tags: views
---


# Question
Title: What permission restricts access to run updates in Drupal 7?
I have a role in my Drupal site that I don't want to access the Drupal database updates. I can't seem to find the permission for "Run updates". What permission restricts access to this page (update.php)?

# Answer
> 3 votes
The permission is **Administer software updates**

# Answer
> 2 votes
Go to **settings.php** file and set

```
$update_free_access = FALSE;

```

After doing this only roles that have "Administer software update" permission will be able to see the "Run updates" tab.

---
Tags: 7, updating
---


# Question
Title: How to create many workbench moderation flows / scenarios
I want to manage many content types with the workbench moderation module. Every content type should have its own states and transitions. I tried Workbench Moderation Profile module, but it has many bugs (it's in alpha) that causes many problems for me so I'm looking for any alternatives.

I don't mind developing a custom module, but I don't know how this could be achieved. Are there other solutions here?

# Answer
> -1 votes
I think what you need is Workbench Moderation Types

---
Tags: workbench
---


# Question
Title: How to create a block with views filter form available on each page of the site?
This is for a site of a small real estate agency.

I have a `property_offer` content type set up and *offer type* vocabulary, with 4 terms (Buying, Selling, Put out to lease and Take on lease). Then I have created a view with page display, for the front page of the site it lists all the offers, and there is also a page for each of the 4 terms.

How do I create an exposed filter for this view which must be available as a block so I can put it in a region of the site and it'll be available on all the other pages too?

# Answer
> 3 votes
Views support "Exposed form in block", see in views editing page. Set it to "Yes", and it will appear in blocks.

# Answer
> 1 votes
Have you tried "Exposed form in block: " in your views setting and set that to yes. This will make a block available in the block menu that has the filters in for that view. The png in this post shows you where. http://drupal.org/node/349099

# Answer
> 0 votes
There is a module called Better Exposed Filters which gives you greater control of views filters.

# Answer
> 0 votes
As mentioned by user348, Views \> Advanced Options \> Exposed Form in Block needs to be enabled. Note that first, Views \> Advanced Options \> `Use AJAX:Yes` must be set **WITH at least one Views \> Filter Criteria** as `(exposed)` (check box for "Expose this filter to visitors, to allow them to change it").

Afterwards, go to `sitename.tld/admin/structure/blocks` and place it in a theme region.

---
Tags: 7, views
---


title: Migrate multiple source data rows

text:
# Question
Title: Migrate multiple source data rows
Has anyone tried migrating fields with multiple source data rows? In my case, Im migrating values of commerce file field (https://www.drupal.org/project/commerce\_file). It only migrated 1 id where it should have multiple id's. I've checked the query in the source database, it outputs correctly, my problem is upon migration.

Here's what I did.

```
$query->addExpression('GROUP_CONCAT(file.field_file_fid)', 'file_id');

/* … */

$this->addFieldMapping('commerce_file', 'file_id')
        ->sourceMigration('PrivateFile')
        ->separator(',');
$this->addFieldMapping('commerce_file:file_class')
        ->defaultValue('MigrateFileFid');
$this->addFieldMapping('commerce_file:preserve_files')
        ->defaultValue(1);

```

# Answer
> 1 votes
I found out that sourceMigration() doesn't allow multiple data source data rows (but please correct me if I'm wrong). So, I made a custom query in my prepareRow() that somehow works like sourceMigration. Here's what I did:

```

// group concat code
$query->addExpression('GROUP_CONCAT(file.field_file_fid)', 'file_id');

// in field mapping
$this->addFieldMapping('commerce_file', 'file_id');
$this->addFieldMapping('commerce_file:file_class')
      ->defaultValue('MigrateFileFid');

// in prepareRow()
public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  // get the values of the file_id where you used group concat function
  $product_id1 = explode(",", $row->file_id); //convert csv to array
  $product_id1 = array_values($product_id1); //redeclare it to clear its index / optional
  $newsIds = array(); //array where the ids will be stored

  foreach ($product_id1 as $i) { //loop through array
      $getEquivalentId = db_select('migrate_map_privatefile', 'p') //'migrate_map_privatefile' is the migrate map table where the ids of the files are stored
              ->fields('p', array('destid1'))
              ->condition('p.sourceid1', $i);
      $resultOfId = $getEquivalentId->execute();
      foreach ($resultOfId as $id) {
        $newsIds[] = $id->destid1; //store result to $newsIds
      }

    }

    $row->file_id = $newsIds; //the values of file_id will now be $newsIds

  }

```

Hope this would help someone, someday. Cheers!

# Answer
> 0 votes
To migrate multiple values in destination database, we just need to provide source values in array. Migrate module will automatically parse this array and migrate accordingly.

See this : https://www.drupal.org/node/1159234

**As per your code:** You can prepare file id array in *prepareRow()* method of migrate module.

```
$row->file_id_array = array(fid1, fid2);

```

And in *\__construct()* you can do field mapping like below:

```
$this->addFieldMapping('file_field', 'file_id_array');
    $this->addFieldMapping('file_field:file_class')
      ->defaultValue('MigrateFileUri');
    $this->addFieldMapping('file_field:destination_file', 'DESTINATION_FILENAMEs');
    $this->addFieldMapping('file_field:source_dir')
      ->defaultValue($file_path);
    $this->addFieldMapping('file_field:destination_dir')
      ->defaultValue(variable_get('file_default_scheme', 'public') . '://event');

```

---
Tags: commerce, migrations
---


# Question
Title: How can I programmatically remove the file from a managed_file form element?
I have a form where users upload images. When an image is submitted it is validated against various criteria. If the validation fails the user is returned to the form but the failed file is still showing in the file upload element with the remove button.

I have been trying to find a way (with no success so far) to automatically remove the file if it fails validation so the user does not have to do it.

It doesn't bother me but the client has requested it so I need to do it somehow.

Any ideas?

# Answer
```
hook_field_widget_form_alter(&$element, &$form_state, $context)

```

this may help you to validate your file and if validation criteria fails return empty form element.
> 0 votes

---
Tags: forms, files
---


title: Subtraction of two column in views

text:
# Question
Title: Subtraction of two column in views
How to subtracts two column in view?
for example:
say column A and Column B need to subtract i,e `[column A - column B]= column C`.How can I achieve this is there any module available for it?

# Answer
Add another field, select `Math Expression` from `Global` group, then in there put something like `[field_1_total] 2 [field_2_total]`

there is not need any addition module
> 2 votes

# Answer
You can try using Views Calc.
> 0 votes

---
Tags: views
---


title: Taxonomy menu block order

text:
# Question
Title: Taxonomy menu block order
I have a Taxonomy Menu Block, displaying the whole tree of a taxonomy category.

However if I change the order of the taxonomy terms it does not affect the Taxonomy Menu Block. Does anyone know if it is possible to make the Taxonomy Menu Block sort the terms in the order they are sorted in the taxonomy tree..? An illustration of the problem:

My menu block is showing:

```
Item A
Item B
Item C

```

If i then go to the tree of taxonomy terms and move Item C above item B like this:

```
Item A
Item C
Item B

```

the Taxonomy Menu Block still shows:

```
Item A
Item B
Item C

```

# Answer
if this module does not respect the order, try to make a view and use its block. see here: https://stackoverflow.com/questions/3806028/drupal-taxonomy-block-vocabulary-listing
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Count of the number of nodes tagged with a particular status
I have a content type called promise whose node can be tagged with a status: not started, in progress, achieved, broken.

I wish to show a count for each of the above statuses in a view block. So say there are 100 promises, I want it to show the following.

* 90 of 100 promises are not started
* 2 of 100 promises are in progress
* 3 of 100 promises are achieved
* 5 of 100 promises are broken

How can I go about this? I know how to count a taxonomy term and show it has 2, 3 or 18 nodes tagged against it, but how to show out of 100?

# Answer
To do this without code, I think you'd need a view for each category and then in the footer or header, choose "Global: Results summary" and build your message there using the tokens. I saw you post about colours elsewhere so if you have a separate block for each, you can then theme each one as you wish.

If you set the view to "Display All Items" and then add css `.viewname .view-content {display:none;}` or a custom module to hide the results, it should work nicely.

You could then use some caching to minimize the performance hit.
> 1 votes

---
Tags: views, nodes, taxonomy-terms
---


# Question
Title: Number of contents created by a user in a organic group
I am using organic groups. I have an organic group called A and its group content B. Users have subscribed to group A and created content for content type B.

Now, I created a view of users. There are three columns. One for the usernames.Second one for the uid. And in the third one I want to show the number of nodes of type B created by a user. There is a contextual filter for organic group A.

I am unable to craete the view. Please help.

# Answer
> 0 votes
If you are happy to use the rules module or the user points module, this is relatively simple. I don't think it's possible using only views.

I would add an integer field to User and have a rule

```
Event: After Saving New Content
Condition: Entity is of type > Content Type B
Action: Calculate a value > Input 1 = site:current user:field / Operator + / Input 2 = 1

```

Then display that field in your view.

User points is another option but is unnecessary if you already use rules.

---
Tags: views, organic-groups
---


# Question
Title: How do I add javascript code to number field?
I have a Number type field in webform for phone number, in chrome it does not allow to enter characters while in mozilla it allows and on submit it shows "enter number" message. now i need to add this script to the webform field so that in mozilla also it wont allow adding characters.

Only numbers please:

```
<input type="number" name="someid" onkeypress="return isNumberKey(event)" />

  <script>
    function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
return true;
 }
</script>

```

how can I use this script in `hook_form_alter()`?

# Answer
> 0 votes
If you are using custom module then you add following code :

```
/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webformCustomID')) {

    $form['#attached']['js'][] = drupal_get_path('module', 'custommodule') . '/custom.js';
  }
}

```

OR

You can do by using module

Webform Javascript Field

> With Webform Javascript Field you can use custom JavaScript or Jquery snippets for all your Webform form elements.

---
Tags: javascript, webforms, forms
---


# Question
Title: Return table and item-list, but only table is displayed
```
$build['table'] = array(
  '#theme' => 'table',
  '#header' => array('A','B','C'),
  '#rows' => $items
);

$build['itemlist'] = theme_item_list(array(
  'items' => $products,
  'attributes' => array('id' => 'my-custom-listing','class' => 'custom-class another-custom-class'),
  'title' => "Bonieren:",
  'type' => 'ul',
  'container_id' => 'bonieren',
));

return $build;

```

Above is my code. The problem is that only the table is being shown on callback. Why does it happen?

# Answer
Your are mixing render arrays and html, use for both table and itemlist the same:

```
$build['itemlist'] = array(
        '#theme' => 'item_list',
        '#type' => 'ul',
        '#items' => $products,
        ...,
);

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to remove the containing "response" tag from GET output
It seems whenever Drupal 8 generates an XML output it gets wrapped in `<response>` tags. I'm defining a custom rest resource (e.g. like this) and can see no way of modifying this containing tag. The service which is consuming the XML feed breaks when it encounters this tag. Is there anyway I can remove it?

# Answer
> 0 votes
Rest plugins always use the standard seralization methods, you can't really influence that for just your plugin. You could implement your own, like ?\_format=my\_fancy\_xml.

Or, if you have very specific needs an an existing client that you need to work with, you can always just implement a normal controller and build the XML yourself and return it with a normal Response object.

---
Tags: 8
---


# Question
Title: How to display all the events in a week view of a calendar?
I have calendar installed on my site. I have created a content type named events. The events content type has three fields title, event time(time only not date and its of type time) and day.

I have modified the block of the calendar view. I have selected the week from calendar format settings so that it should display the week view.

Now I want to list all the events under the monday which have the monday selected in the day field, all the events under the tuesday which have the tuesday selected in the day field and so on.

**Format:**

Mon tue Wed Thu Fri Sat Sun

event1 event2

Monday Tuesday

2:30 2:30

# Answer
> 1 votes
Calendar module creates a node for each day.So all you need to do is create a field of type date in your content type and then create nodes.

Alternatively,you can try using jquery fullcalendar plugin(http://code.runnable.com/UfNTSnKMU1ZgAACt/how-to-add-calendar-using-jquery-and-fullcalendar) and provide data for each day programmatically.

# Answer
> 0 votes
You can try creating a view with. The FORMAT could be "Table" and you have to use on the setting "Grouping field Nr.1".

On Grouping field Nr.1 you can select your day field.

I hope it's what you are looking for.

---
Tags: 7, datetime
---


# Question
Title: Why does my Quiz rule stop working after adding an extra user profile condition?
I have a Drupal 7 site, that uses Rules and Quiz. I have a rule that adds a role after the user takes a specific quiz, which work fine. Here are the details of it:

* **Event**

After updating existing content
* **Conditions**

*Content is of type*

Parameter: Contenido: \[node\], Content types: Cuestionario

*Data comparison*

Parameter: Data to compare: \[node:nid\], Data value: 1985
* **Actions**

*Add user role*

Parameter: Usuario: \[site:current-user\], Roles: nivel2

Now I want a similar rule but add the new role only if a specific profile field in the user's profile, has specific content. The field is a selection of certain terms of a certain taxonomy.

So, I've cloned the above (working) rule, and added to it a condition. So that this new rule looks like so:

* **Event**

After updating existing content
* **Conditions**

***Data comparison***

***Parameter: Data to compare: \[site:current-user:profile-profile:field-ubicacion, Data value: Provincia de Chaco***

*Content is of type*

Parameter: Contenido: \[node\], Content types: Cuestionario

*Data comparison*

Parameter: Data to compare: \[node:nid\], Data value: 1985
* **Actions**

*Add user role*

Parameter: Usuario: \[site:current-user\], Roles: nivel2

Now in this case, this new rule won't work. I.e the role is not added.

Why could this be?

# Answer
Make sure to add a Rules condition `Entity has field` (related to your additional field in your first Rules condition). And make sure to add that `Entity has field` condition BEFORE the condition in which you want to perform that "data to compare".

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.
> 1 votes

# Answer
> The field is a selection of certain terms of a certain taxonomy.

"Data comparison" is for fields with one value. (Or maybe an exact match of multiple values.. I'm not sure.)

Anyways, use the condition "List contains item" for fields with multiple values. And use a few of them if you need to check for more than one term.
> 0 votes

---
Tags: 7, rules, users, quiz
---


# Question
Title: Adding Class to views row if View style is Unformatted list / Content
I need to add a CSS class to a views row depending on a field. So far this is easy going if I use Fields as Content (add class via replacement patterns then).

But I find it far more difficult to do this when using Row style "Content" and a custom view mode (e. g. Teaser).

I found the following code to work for me if I use Row style "Content":

```
function mytheme_preprocess_views_view_unformatted(&$vars) {
foreach($vars['view']->result as $rkey => $rval)
{
    $node = node_load($rval->nid);
    if(isset($node->field_breite) && !(empty($node->field_breite)))
    {
        $vars['classes_array'][$rkey] .= $vars['classes_array'][$rkey] . " " . $node->field_breite[LANGUAGE_NONE][0]['value'];
    }
}

```

}

**I like to ask if this is a suitable approach or am I maybe wasting resources by loading each node and can I grab the node data easier somewhere else?**

PS: It is not a option for me here to use Fields in the View as content because I want to use different content types in the view with different fields.

Settings:

# Answer
> 1 votes
You can try do this later in process or template, when the `$vars['rows']` is flattened. You can pull all instances of `field_breite` out of the flattened row and put them into the classes of the row. For this the `field_breite` has to be in the custom view mode of course. This would be not so nice for coding, but much faster.

I would code it like this in `mytheme_process_views_view(&$vars)`, but I'm sure you need some debugging:

Go row by row in $vars\['rows'\]. Search the complete field with preg\_match() by using the html tags of the field and set parenthesis in the regular expression to get the field value in $matches\[1\]. Add the field value in $matches\[1\] to $vars\['classes\_array'\]\[$id\] to set the row class. Cut the complete field out of the row with str\_replace() by using $matches\[0\] from the first search and an empty string.

---
Tags: views, theming
---


# Question
Title: Warning: Cannot modify header information - headers already sent
My log is cluttered with this message:

```
Warning: Cannot modify header information - headers already sent by (output started at /home/path/to/drupal/7/includes/common.inc:2681) in drupal_send_headers() (line 1216 of /home/path/to/drupal/7/includes/bootstrap.inc).

```

It occurrs only when someone types address to a non-existing comment like this:

```
http://example.com/comment/874

```

If the comment exists, or for any other address, there is no error. (I was deleting lots of spam comments recently and the bots keep coming back to read their own comments, that's why there is a lot of not found comments.)

Is there any means to get rid of this error? The only comment module I have is Comment Goodness and there isn't complaint on such error in the issue queue, so maybe it's something else. I checked all my custom module files and each of them starts with `<?php` and there is no space or anything before this tag, and there is no closing tag. I have no idea what else to check.

# Answer
In my own case, I've found that this was due to modules that attempt to return a 404 by mistakenly calling drupal\_not\_found() instead of returning the MENU\_NOT\_FOUND constant. This causes drupal\_deliver\_page() to be called twice in a single page request.

Views is the biggest culprit right now; see https://drupal.org/node/1414068 (comment #16) for a patch that resolves it. You should grep through your modules directory for "drupal\_not\_found" to find other modules with this problem.
> 6 votes

# Answer
I have seen a few things cause this.

A closing `?>` on a file with space after it. The Drupal convention is to not use the closing PHp tag on any file.

A UTF-8 encoded file with a BOM. The BOM would be before the the opening `<?php`, and is output.

Following the advice of Yahoo! YSlow and adding a `flush()` between the `</head>` and `<body>` in html.tpl.php

Debug directly using `print` or `print_r` instead of `dsm()` in code.

I also recall a weird problem I had where I had some framebusting code in a template file, and if a linked resource 404ed, then I think I had this problem b/c the Drupal 404 page would load for the linked resource.
> 3 votes

# Answer
Building on Les Lim's answer, combined with your finding that you are seeing this with comment URLs, you are probably seeing issue #2218501 from the Comment Goodness module (are you using that on your site?). It is inserting its own callback for comment URLs and is indeed calling drupal\_not\_found() when it can not find the comment (where it should be retuning MENU\_NOT\_FOUND).

There is a patch in the issue, and it has been committed to the development branch of the module, in october of 2014. Looking from the project status and the issue queue, it doesn't look like we can expect an updated official release any time soon, though.
> 0 votes

---
Tags: 7, comments
---


# Question
Title: How to trigger a rules action only for a specific value of a user profile field?
I have created a Rules component which contains an action to send an mail.

And I have a rule created with the scheduler option. In this rule, I have set one condition like so:

> **if** site:current-user field has value equals to something
>
> **then** mail should be triggered,
>
> **otherwise** it should not.

But it is sending an eMail in both cases. Any idea why?

# Answer
> 1 votes
Make sure to add a Rules condition `Entity has field` (related to your additional `site:current-user`-field in your Rules condition). And make sure to add that `Entity has field` condition BEFORE the condition you already have.

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

---
Tags: users, entities, rules
---


# Question
Title: Rules sends email to mailto link instead of email address
I've created a content type with an email field. Anonymous users are allowed to create these nodes. I've created a Rule that sends an email message to the value submitted in the node's email field, using a replacement pattern. Rules tries to send the email to a mailto: link, not to the email address. The outgoing mail fails with the sendmail error: "Cannot mail directly to files", because it is addressing the email to the link, not the address.

# Answer
> 0 votes
Click the button that says "Switch to Data Selection" and choose the Data Selector corresponding to your email field, not the Replacement Pattern.

That way the Rules module will send the email to the actual email address, instead of to the 'mailto:'-link.

---
Tags: rules
---


# Question
Title: How to programmatically access the allowed HTML tags in Filtered HTML
A bit of an oddball question. In Drupal 7, I have a comment form page that is required to show the allowed HTML tags available to users. The default list has been added to over time so now I have about 40 different tags.

I want to display it programmatically as part of the form, but I cannot give users the option to change the text format (I want them to use the default Filtered HTML) so I've hidden the Text Format portion of the comment form using the Simplify module.

So my question is how can I output the revised list of allowed HTML?

I've rummaged through the filter module, and tried to print the results of filter\_filter\_info() like so:

```
$filter = filter_filter_info();
print_r($filter);

```

but all it returns is the default list of tags that comes with vanilla Drupal, maybe 10 tags or so. It doesn't show my revised list of tags at all.

I've searched for quite some time but can't find any info on how to do this, so any help would be appreciated!

# Answer
> 1 votes
```
$filters = filter_list_format('filtered_html'); // put your filter name here
$tags = isset($filters['filter_html']) ? $filters['filter_html']->settings['allowed_html'] : FALSE;

```

---
Tags: 7, input-formats
---


title: Adding/deleting from data tables

text:
# Question
Title: Adding/deleting from data tables
I have a few data tables on my site. If I login as the admin and go to the page where the view of the table is located, I can click Edit Item and change that one entry. However, I can't find how to add new or delete entries that are there.

When I'm looking at my data table screen I can see this:

```
TITLE         - NAME         - NUMBER OF ROWS
Example Title - Example Name - 41             - View

```

However, when I click View, it basically just refreshes the page and doesn't let me view the table. This happens for all my tables. If I'm at the Data Table Management page, I can do everything that is listed there (edit the table itself, claim/disown, schema, etc), but there's no option on this page to edit the data in the table. It says I should be able to do that from the Data Table Content Page. I realize I can edit these entries directly from the database, but the hope is to give an admin user of the website the ability to manage this data table without giving them access to directly edit the database itself.

Any suggestions or possible alternative solutions that I could use?

# Answer
The data table must be marked as a Drupal Entity -- then the columns of the table may make use of the Field UI to allow an edit page per entry similar to a node\_edit form.

Otherwise, you may be able to use the Editable Views module to make a table redition of your Data table -- whose cells are editable values. In this case you will likely still need to make the whole table a drupal entity.

The Data module is an API module to adopt/destroy SQL tables into Drupal. It's not really designed as a phpmyadmin replacement for a site.
> 0 votes

---
Tags: database
---


# Question
Title: Is it possible to get rid of the Javascript code?
All nodes (Drupal 7) contain the following code:

```
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/misc/jquery.js?v=1.4.4"></script>
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/misc/jquery.once.js?v=1.2"></script>
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/misc/drupal.js?nxe6cr"></script>
<script type="text/javascript" src="http://localhost:8080/myfeodor.de/sites/default/files/languages/de_HizaMms-3Ux-y0M1w9o2_EvSFCBziqwcKzQq9_kzJ78.js?nxe6cr"></script>
<script type="text/javascript">
    <!--//--><![CDATA[//><!--
    jQuery.extend(Drupal.settings, {
        "basePath": "\/myfeodor.de\/",
        "pathPrefix": "",
        "ajaxPageState": {
            "theme": "my_garland",
            "theme_token": "WTVBB9vMIjxgWuVheFjYXjuvpo1TgahCH62PRBBFGrA",
                "js": {
                "misc\/jquery.js": 1,
                "misc\/jquery.once.js": 1,
                "misc\/drupal.js": 1,
                "public:\/\/languages\/de_HizaMms-3Ux-y0M1w9o2_EvSFCBziqwcKzQq9_kzJ78.js": 1
            },
            "css": {
                "modules\/system\/system.base.css": 1,
                "modules\/system\/system.menus.css": 1,
                "modules\/system\/system.messages.css": 1,
                "modules\/system\/system.theme.css": 1,
                "modules\/comment\/comment.css": 1,
                "modules\/field\/theme\/field.css": 1,
                "modules\/node\/node.css": 1,
                "modules\/search\/search.css": 1,
                "modules\/user\/user.css": 1,
                "sites\/all\/themes\/my_garland\/style.css": 1,
                "sites\/all\/themes\/my_garland\/print.css": 1,
                "sites\/all\/themes\/my_garland\/fix-ie.css": 1
            }
        }
    });
    //--><!]]>
</script>

```

The file `de_HizaMms-3Ux-y0M1w9o2_EvSFCBziqwcKzQq9_kzJ78.js` contains an associative array where error messages are translated. But this appears not to be necessary since the page works also with scripting deactivated in the browser.

This is WAMP, but under Linux the same code appears.

This code is also present if one is only reading without being logged in. Is is possible to avoid this scripting?

Drupal 6 has been Javascript-clean for readers.

# Answer
At drupal.org user *Jaypan* propsed to implement a new module (named e.g. killjs) which would have to implement hook\_js\_alter()

```
<?php
function killjs_js_alter(&$javascript) {
  // Insert code to check whether JS should be killed or not.
  $javascript = array();
}
?>

```

This, however, would be very laborious for non-experts since it would be necessary to do a more or less complete analysis of the Drupal code base first. User *leymannx* proposed a solution which may be realized without developing a new module:

* Javascript is deactivated only for a specific theme, here called custom\_garland.
* Copy file modules/system/html.tpl.php into the customized theme folder as /sites/all/themes/custom\_garland/html.tpl.php.
* In the copied file html.tpl.php delete the line `<?php print $scripts; ?>`.
* Clear the drupal cache.
* Select custom\_garland as default theme.

Now for guests the page is clean of Javascript! In the backplane, Javascript is still active due to file maintenance-page.tpl.php. This means one can still adust the Garland/Bartik colors or drag blocks.

For me, the maintenance mode works with the above modified theme. *Stefan Korn* presented a refinement of this apporoach where JavaScript is fully activated for users which are logged in.
> 2 votes

# Answer
If you only want to delete the javascript for anonymous user you could easily go like that in html.tpl.php:

```
<?php if($logged_in == 1): ?>
  <?php print $scripts; ?>
<?php endif ?>

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: WYSIWYG editor not actually able to make use of all its tools
I've enabled my WYSIWYG editor for my authors on my site so that it uses filtered HTML format (using better formats module to ensure they use that text format).

However, while testing I note that when I use the WYSIWYG editor to input content, like new lines, tables, etc...the formatting doesn't actually 'take'. Certain things like links get set ok and bolded items...but not all the tools available in the CK editor WYSIWYG are showing correctly when the item is unpublished or published. When I go back to edit the item the HTML is all still there...but for some reason it doesn't display as if it's using the HTMl.

Thoughts on this?

# Answer
You need to go to

```
/admin/config/content/formats/filtered_html

```

and add the html tags under allowed tags.

Then under Limit Allowed html Tags add `<form> <input>` into the list.

**IF The above does not do it**

go to:

```
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

```

Then under Advanced Content Filter, select disabled.
> 1 votes

# Answer
Filtered HTML format restrict some HTML tags, inspect or check source code of your text and see what is new line converted to.

**Few guidelines for WYSIWYG editor:**

* Try Full HTML format
* Check with permission on HTML profiles, on this path: admin/config/content/formats
* Check your jQuery version, use jQuery update module
* Check is there any JS error on console
> 1 votes

---
Tags: theming, wysiwyg
---


title: Auto Apply credits at checkout

text:
# Question
Title: Auto Apply credits at checkout
I am using commerce\_userpoints which allows the use of credit to discount the amount at checkout of a product.

Right now the user needs to do this manually however I would like to automate this.

Any clue on how can I get this done ?

# Answer
Use rules. When the order is completed, use the actions contained in the `userpoints_rules` submodule to manage your userpoints. You might choose the "When an order has been paid in full" or you could just watch for orders moving in status to "Completed."
> 4 votes

---
Tags: commerce, userpoints
---


# Question
Title: How do I pass a variable via drupal_goto()?
So I have a function having `http://link/to/$id` as destination link.

It works when I use `<a href="?q=mymodule/option/$id">Targeted</a>`.

But I need to change it to submit form because I need to pass more than one `$id`. So, I thought it was good to use `drupal_goto()` rather than the link option.

```
drupal_goto('mymodule/option/$id');
drupal_goto('mymodule/option/'.$id);
drupal_goto('mymodule/option/', $id);

```

Those are not working. It always go to http://link/mymodule/option without passing `$id` variable. How do I do this correctly?

# Answer
Assume your url is like in this example:

```
http://example.com/somepage?param1=val1&param2=val2

```

In that case you can take values of `param1` and `param2` like so:

```
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];

```

You may use this parameter for drupal\_goto as

```
drupal_goto("path_here", array("param1" => $param1, "param2" => $param2));

```

**For Drupal 7:**

As YPCrumble says you need to use this code:

```
drupal_goto("path_here", array("query" => array("param1" => $param1, "param2" => $param2)));

```

For more details, refer to the API Documentation.
> 7 votes

---
Tags: 6, redirection
---


# Question
Title: How to change head title of a page having a Omega 4 subtheme?
I'm trying to implement this: http://ryanissamson.drupalgardens.com/blog/html-node-and-view-title to add the possibility of having HTML injected in node titles. It works great for the node titles in the pages and the views.

But there's something I cannot accomplish: the "$head\_title" part. I can't change the text of the title showed in the browser tab, so, assuming that I have a mid-italic title like "Ti*tle*", in the browser tab it shows something like "Ti\[i\]tle\[/i\]".

I think it's because Omega 4 uses the Layout system, that works perfect, and we don't have to override page.tpl.php, as seen in How do you override page.tpl.php in Omega 4?

Here people say to this guy to disable Layouts, but for me that's not an option at this moment.

Any ideas? Thanks.

# Answer
> 0 votes
Changing head title for a page in Omega 4 based on node id - same approach will work for any other content. (code below goes into template.php)

Didn't test if this method supports described above HTML injection.

```
    function yourtheme_preprocess_html(&$variables) {
        if ($node){
        $mynodeid = $node->nid;
// this will set "Custom Title" for a node with NID = 10
        if($mynodeid == 10) {
            $variables['head_title'] = t('Custom Title');
        }
      }
    }

```

---
Tags: theming
---


title: Search module for taxonomy terms?

text:
# Question
Title: Search module for taxonomy terms?
Having browsed through drupal.org with no results for D7, let ma ask the public: does anyone know of a Search module that would extend the search by taxonomy terms? I have a very taxonomy-intensive site, where each taxonomy term has a rich description field, as well as its own term page. I want user to be able to find not only nodes but also taxonomy terms.

# Answer
> 2 votes
I'd highly recommend using Search API with which you can create an index and custom search from any entity including Taxonomy terms. You can then customize your search page using Views.

# Answer
> 0 votes
Try Custom Search Included submodules Custom Search Taxonomy: taxonomy options for the search block Custom Search Blocks: provides additional search blocks, with different settings Custom Search Internationalization

# Answer
> 0 votes
We faced a similar challenge where a large number of taxonomy terms contained valuable content that was not caught by the Drupal search index net. Our solution involved a small custom module. The module defines a custom content type with only a title field and term reference field. After a sitebuilder creates this custom node and chooses a taxonomy term to reference the standard node-centric index and search mechanism will find and display the custom node which contains only the title, term description as defined by referenced term, and a link to the taxonomy term page. By design this module requires a node to be created for each taxonomy term that the site builder wants represented. We created these nodes manually as not all taxonomy term descriptions were populated.

This basic module code is in 'sandbox' status.

https://www.drupal.org/sandbox/dwaine/ttnode

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


# Question
Title: How to get an anonymous user session id?
I am writing a chat module where anonymous users are able to chat with a logged in user via an external websockets connection.

I need an ID to uniquely distinguish the anonymous users and assign them to different connections and keep track of the status of the connection.

How do I (securely) get a unique user id or session id for an anonymous user ?

# Answer
You're looking for PHP's `session_id()`:

> session\_id() is used to get or set the session id for the current session.
> 13 votes

# Answer
Drupal stopped tracking anonymous sessions a few versions ago. If you want to trick Drupal into doing it again you need to make a module with a custom `hook_init()` implementation.

```
/**
 * Implements hook_init().
 *
 * <soapbox>The Drupal team decided to remove support for anonymous user sessions
 * starting in Drupal 7.37. This fundamentally breaks several things related to Drupal.
 * I cannot find any documentation of this change in any changeme dating back to 7.33.
 * The answer comes to us from:</soapbox>
 *
 * https://dgtlmoon.com/drupal_7_anonymous_sessions
 */
function mymodule_init() {
  drupal_session_start();
  $_SESSION['nosave'] = TRUE;
}

```
> 4 votes

---
Tags: sessions
---


# Question
Title: How to send email invite user fill in webform automatically?
I'm using drupal 7, and had a seminar questionnaire form created using webform.

I would like to invite seminar attendee to fill in this questionnaire after they attend the seminar, by sending them email with link to the questionnaire.

Rather than manually open my email client and retyping the same invitation template for every seminar, is there anyway I can have this?

* A standard template of email invitation content with webform link
* Admin only need to type in different email address of each seminar
* Email will automatically sent to address entered
* Attendee do not need token or account to fill in the form
* It's similar to google form share this form / invite through email function

Is there any module to do this? Or I need to use with other modules such as Rules?

# Answer
There are a handful of different modules that can let you do bulk emailing (e.g. VBO, Mass Contact, Email Campaigns, etc.), but using Drupal as a batch email client I think only make sense in the context of:

* Having regularly visiting user base, with pre-existing accounts.
* Needing to contact a relatively small number of people (e.g. hundreds, or very low-thousands).

Your 4th requirement suggests that you'll be supplying any number arbitrary emails for the sake of feedback/lead gathering.

In lieu of a module or Rules (which only make sense in the context of some workflow built into the site), I'd suggest some 3rd-party email service (e.g. Constant Contact, MailChimp, etc.) to accomplish items #1-4. Any decent 3rd party email service should give you a templating system with substitutable tokens that will let you customize your webform link if you need it to have pre-filled data (e.g. email, name, attended seminar, etc.) and a means to bulk submit email/contact info.

As far as item #5, there's a number of different way to accomplish this. One way is the Forward module which provides a share via email link/form for any node type.
> 0 votes

---
Tags: 7, webforms
---


title: Payment method differences by subdomain

text:
# Question
Title: Payment method differences by subdomain
I am trying a configuration where I have drupal commerce setup in different subdomains representing different stores using domain access and domain access entity.

My issues is that when i enable paypal wps rule as payment method, the same information that I have for receiver in one subdomain is copied over to all subdomains. Is it possible to have a unique payment method details by each subdomain? So products purchased from one subdomain are processeed by its own unique payment method details? Can rules be used to identify which domain the order is from and process it for payment details for that domain?

# Answer
> 0 votes
Looks like the Domain Rules module provides a condition so that you could limit a configuration by a domain.

---
Tags: commerce, rules, domain-access, subsites
---


title: Create a mock Form for WebTestBase?

text:
# Question
Title: Create a mock Form for WebTestBase?
Is there a way in the testing framework to define a generic form intended only when tests run?

I have created some custom form item Element classes. I have working Unit tests with them, but I would also like to provide Simpletests for them as well.

# Answer
Core provides several examples of this. The basic pattern is to create a test module, and have that module provide the form. In your test `::setUp()`, you add the test module to `$modules`, and then your form should be available for use.

Look through 'core/\*/tests/modules' for the test modules, and if you have an IDE that class completes, a lot of the test form are (wait for it) `TestForm`.

However, in your case, I would look at existing Element classes and see what their integration tests look like. I suspect you can just emulate what they are doing w/o needing your own test module.
> 2 votes

---
Tags: 8, testing
---


# Question
Title: How to edit order summary field labels on paypal page
My company sells online services and I have been able to limit my customers to buy one service at a time with the help of rules. However, when my users are directed to paypal, following information is presented to them on the paypal site:

Is there a way I can edit paypal label ‘item price’, as can be seen in the above shot, to something else such as ‘service charges’. Also can I remove the quantity field all together, as my users are unable to purchase more than one service at a time. No point to show the quantity to them.

I am using following code to remove quantity field, but it still appears on paypal. Also, I am unable to find the field label: item price in this hook.

```
function checkout_forms_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
unset($data['on0_1']);  //to remove options
unset($data['os0_1']);  // to remove quantity field
}

```

# Answer
> 1 votes
The Paypal WPS API can be used to hold multiple individual items, but it can also just be used to handle a single order. It effectively does this by making the Drupal order the only product on the PayPal order.

If you are wanting to customize checkout further, you'll need to find another processor that gives you that ability. PayPal PayFlow Pro or some other option might work.

---
Tags: commerce, payment-gateways
---


# Question
Title: Simplenews Scheduler Sending Newsletter Twice a Week
I'm having trouble configuring how to send a simplenews newsletter to subscribed users twice a week. I'm using Simplenews scheduler but just don't know how to configure it. I want to send a newsletter of all my updated content to my users on Sunday and Thursday.

I've got everything else working, just don't know how to configure it to send on Sunday and Thursday. In Simplenews Scheduler, we can schedule it to start sending on a specific day like Sunday and set the Sending interval to 'Day', then, set Interval Frequency to 4. But I am certain that after the first two times, the days will shift and the third time it will send on Monday and fourth time on Friday and just keep shifting a day each time.

So, hope you guys have some ideas on how to configure it correctly.

# Answer
There is a way of solving it without Rules, you can use Simplenews Scheduler.

Simply create two different Simplenews nodes of the same Simplenews category. You can use the same views token (or whatever you use to fill in the content of the newsletter) in both nodes.

Then set one node to send on Sunday weekly, and the other on Thursday weekly.

This can be done because Scheduler is set per node, not per category, and also subscribers are subscribed to Categories, not nodes, so each time all of the subscribers will receive the news, no matter if Sunday or Thursday nodes happen to be sent.
> 0 votes

---
Tags: emails, cron
---


# Question
Title: Some variables not listed when creating feature
I'm building a feature that includes modules settings stored as variables. Strongarm module is great for that but for some reason, pathauto\_entity's module variable called `pathauto_entity_available_entity_types` is not listed as available strongarm variable when I'm creating new feature.

The variable is listed on Strongarm's admin page when I go to `admin/config/development/strongarm`.

Any ideas why this is happening? Is it strongarm or maybe CTools issue?

The variable exists in database and I can read it with drush without problems.

# Answer
> 0 votes
If that variable is showing up in the Strongarm admin page, then it means that it's already strongarmed - it probably already exists in another Feature. Use the grep command to search for instances of it in your codebase:

`grep -irn 'pathauto_entity_available_entity_types' [codebase-dir]`

I bet that will turn up an existing Feature that is managing that variable.

You can't export the same variable to more than one Feature. But you can override it with the Features Override module.

---
Tags: 7, features, strongarm
---


title: Views relationship using taxonomy

text:
# Question
Title: Views relationship using taxonomy
I have two content types (document and employee) and both have a reference to a taxonomy (language). I would like to build a view showing all documents that a employee could read. In other words, both of them have the same language.

I've try to relate the employee and the taxonomy; however, I can't see a way to relate the taxonomy to the document. I've also tried to relate directly the employee language ID to the document language ID, with no success.

Do you have any idea to solve this problem?

# Answer
> 2 votes
I thing you need to sort the node using the taxonomy fields. Is it so then use the steps:

1. Add realtionship in views
2. Then add 'taxonomy terms on node'
3. Then go to filter then you can find all the terms there

# Answer
> 1 votes
EVA module can help you with that. It enables you to attach a views display to an entity, and pass arguments from the entity to views to filter the views results.

With it you can create a list of documents, set the views display to show on employee content type, and set the taxonomy term as the filtering argument.

You can find more details about how to set it up here: EVA field: file entities filtered by taxonomy term of attaching node

# Answer
> 0 votes
Try adding an Argument for *Taxonomy: Term ID* and provide Default Arg - PHP

Then paste this code:

```
if (arg(0) != 'node') {
  return;
}
$node = node_load(arg(1));
if ($node && $node->taxonomy) {
    foreach($node->taxonomy as $term) { $terms[] = $term->tid; }
    return implode('+', $terms);
}
return;

```

Source

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


# Question
Title: How to give to the users the opportunity to change role as desired
As the title says, I would give to members a way to **choose their own role** as required **via radio buttons** in their **profile page**. Any suggestion?

# Answer
You can do this with rules.

```
Event: After saving user profile
Conditonal: field has value
Action: Assign role to user

```

Something long these lines. You will need to create a new rule for each role unless you do some special field-value handling. You will also need to create a few checks in here to prevent the rule from re-assigning a role to a user.
> 1 votes

# Answer
The Role Delegation module should actually get you most of the way there. You would have to create a custom module to implement `hook_form_alter()` and change the role selection from multiple checkboxes to single radio buttons.
> 0 votes

# Answer
If there aren't too many roles, I would create a taxonomy with a term for each role. Then add a taxonomy term field to the User. Then I'd create rules for "user profile updated" to apply each role.
> 0 votes

---
Tags: users
---


# Question
Title: Convert links in content to internal form?
If I create a hyperlink inside a text field (such as node body) with an internal path uri such as "node/1234" or "index.php?q=taxonomy/term/5678", then I can use an input filter such as pathologic to convert that uri at display-time to the preferred alias uri, such as "http://example.dev/path/to/my/content"

(I would consider this a more resilient way of storing content than using the full aliased uri)

However, I can't see an easy way for a non-technical user to find an internal path uri and paste it in. Is there any way to get drupal to spot when a user has inserted an alias-based link into the content, and convert it into an internal path uri before saving to the database? I know the menu module does this with links, using drupal\_get\_normal\_path(), but can it be done for html links in the content? Ideally with an existing D7 module?

For example, content like `<p>More info at <a href="http://example.dev/info">this link</a></p>` would be converted to `<p>More info at <a href="node/123">this link</a></p>` before saving into storage.

Also, is there any existing online discussion about the advisability of this approach?

# Answer
> 1 votes
In terms of non-technical (which I read as custom development) solutions, what you're describing is one of the features of LinkIt.

> Linkit provides an easy interface for internal and external linking with editors and fields by using an autocomplete field. Linkit links to nodes, users, managed files, terms and have basic support for all entities by default. Linkit has three major advantages over traditional linking

It provides a WYSIWYG toolbar button from which a user can paste a URL for embedding a link. Upon setting up a LinkIt profile for you input type, there's a **Insert paths as** setting with a *Raw paths* option that defaults the inserted link as Drupal's internal path.

---
Tags: navigation, path-aliases, input-formats
---


title: Views Sub tab on user account page

text:
# Question
Title: Views Sub tab on user account page
I am trying to create a menu structure on the user profile page like:

```
/user/%/content = Main tab (next to View, Edit) on /user/%uid
/user/%/content/published = Sub tab showing published nodes
/user/%/content/unpublished = Sub tab showing unpublished nodes

```

I have tried using /user/%/content/all as the main default tab. Tried setting sub tab as default tab and not default.

Ive gotten:

```
    View, Edit, Published, Unpublished, My Content

    View, Edit, Published
                 -Published
                 -My Content

View, Edit, My Content (with no child tabs)

```

I can't seem to find the correct settings to get My Content to be the main tab, with Published and Unpublished to be sub tabs to My Content.

I tried swapping the settings for Published and My Content but that didn't work.

Does My Content need to be the default tab? Or does Publish need to be the default tab with My Content as the "parent already exists"?

Any help getting the tab structure sorted out would be greatly appreciated.

# Answer
Under *Page settings*, in the view settings, you will find the *Menu* option; you need to set it to:

* *Menu tab* for user/%/content
* *Default menu tab* for user/%/content/published
* *Menu tab* for user/%/content/unpublished

>

This is how it appears.

>

### PS

I used the Tracker view that comes with the Views module, and altered it to obtain the desired result.
> 0 votes

---
Tags: 7, views, routes
---


# Question
Title: How to display a field before node title?
I'm looking to render a certain field before the node's title when displaying a teaser in D7.

Effectively I want to go from this to this.

I have looked into updating the node.tpl.php but I notice that it separates `$title` from `$content` so I'm unsure how to approach this. After some searching I have found that people have suggested using CCK and ConTemplate modules to get around this in Drupal-6 but I'm wondering if there is a more Drupal-7 solution.

Any suggestions?

# Answer
> 51 votes
This is really quite simple with Drupal 7.

With `render` and `hide` you know have the posibility to control the placement of a single element in `$content` without having to print out all the items yourself like was needed in Drupal 6.

A simplified node template looks like this:

```
<div>
  <h2><?php print $title; ?></h2>
  <div class="content">
    <?php print render($content); ?>
  </div>
</div>

```

A little modification would handle your needs:

```
<div>
  <?php print render($content['field_name_of_image']); ?>
  <h2><?php print $title; ?></h2>
  <div class="content">
    <?php print render($content); ?>
  </div>
</div>

```

Using `render`, you can output an element. This is more clever than simply printing stuff, as Drupal will keep track of what has been rendered, to avoid the same thing being printed twice on the place. When rendering the field above the title you are also removing for what's rendered when `$content` is rendered.

# Answer
> 8 votes
Display Suite is also pretty cool.

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

# Answer
> 7 votes
Have a look at the Title module - http://drupal.org/project/title. It might prove useful for your scenario. I installed/enabled it for some reason, probably similar to yours, and it seemed to give flexibility of how to place the title field.

I have since disabled it (and am using Display Suite), so my recall might be a bit sketchy.

# Answer
> 4 votes
This is a hackish solution and I'm sure someone will come up with something more elegant, but in case you're stuck, and no one does...

You could use `page.tpl.php` to remove the printing of `$title` altogether, and add a new custom field called Title with machine name $new\_title or something like that. Then on node edit, hide the original Title box, and on node Save use Computed Field or some custom php to copy the `$new_title` to `$title`.

After all that, write some css to make $new\_title look like the page title did before and you should be able to place whatever fields in whatever order you like, just by dragging and dropping in the manage fields screen. Because you copied over `$new_title` to `$title`, the page title in the browser bar should still work and nothing should complain about missing node titles.

Like I said, it's a hack - but it would work. Let me know if you need more info

# Answer
> 3 votes
page.tpl.php (garland)

```
...
      <div id="center"><div id="squeeze"><div class="right-corner"><div class="left-corner">
          <?php print $breadcrumb; ?>
          <?php if ($mission): print '<div id="mission">'. $mission .'</div>'; endif; ?>

          /*
           * Print custom block or var
           */
          <?php if ($custom_block): print '<div id="custom-block" class="clear-block">'. $custom_block .'</div>'; endif; ?>

          <?php if ($tabs): print '<div id="tabs-wrapper" class="clear-block">'; endif; ?>
          <?php if ($title): print '<h2'. ($tabs ? ' class="with-tabs"' : '') .'>'. $title .'</h2>'; endif; ?>
          <?php if ($tabs): print '<ul class="tabs primary">'. $tabs .'</ul></div>'; endif; ?>
          <?php if ($tabs2): print '<ul class="tabs secondary">'. $tabs2 .'</ul>'; endif; ?>
          <?php if ($show_messages && $messages): print $messages; endif; ?>
          <?php print $help; ?>
          <div class="clear-block">
            <?php print $content ?>
          </div>
          <?php print $feed_icons ?>
          <div id="footer"><?php print $footer_message . $footer ?></div>
      </div></div></div></div> <!-- /.left-corner, /.right-corner, /#squeeze, /#center -->
...

```

template.php

```
/**
 * Override or insert variables into the page template.
 */
function phptemplate_preprocess_page(&$variables) {
  $node = $variables['node'];
  if($node->type == MY_NODE_TYPE) {
    $variables['custom_block'] = 'bla bla bla';
  }
}

```

# Answer
> 3 votes
This doesn't apply to the Teaser question in the original post, but for people who stumble across this and just want to make it happen in the full view, here's a code-free option: display the field in a block (using views, for instance) and place that block above your content block but in the same region.

# Answer
> 2 votes
I think you should to use preprocess functions in your template.php

```
/**
 * Override or insert variables into the page template.
 */
function THEMENAME_process_page(&$variables) {
  // look for $variables['page_title'] if i remember
}

```

And as additional

```
/**
 * Override or insert variables into the node template.
 */
function THEMENAME_preprocess_node(&$variables) {
  //
}

```

dump variables and do anything what you want. add/remove/update.

# Answer
> 2 votes
I resolved this by codeless solution using Display Suite and its "Region to Block" extras feature. I like this solution most for its flexibility.

Basically, enable "Region to Block" extras part, enable "Fulltext Content" display in Display Suite. (assuming you want to display content above title in the full-node display, similarly you can use it for any other view mode **except** Default). Now, in "Manage display" part of "Fulltext Content", at the bottom of the screen, the "Block Regions" tab should appear. Enter new block name there, save and drag&drop the desired fields to this block. Lastly, move the newly created block in Blocks screen somewhere *above* the node title.

You can see the video of same approach here: http://www.youtube.com/watch?v=y4wyjxyhbNA , of course you need to place the block above title (not to the left sidebar) at the end.

# Answer
> 1 votes
For zen templates below code works for me.

```
<?php
// this goes in template.php
// check if node type page and then add to $vars array
// declaring $vars['foo'] gives you a $foo variable to use in page.tpl.php

function YOURTHEMENAME_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) :
        if($vars['node']->type == 'page'):
            $node = node_load($vars['node']->nid);
            $output = field_view_field('node', $node, 'field_image', array('label' => 'hidden'));
            $vars['my_image_field'] = $output;
        endif;
    endif;
}
?>

```

So finally, you can easily print your field in page.tpl.php;

```
<?php
if ($my_image_field):
   print render($my_image_field);
endif;
?>

```

# Answer
> 1 votes
I know you would have already used some theme to build and now trying to add the fields at the top of title.

My Suggestions to all developers building theme on Drupal 7 would be to use: Omega theme + Context and Delta modules. This gives a very strong foundation for your layout.

And flexibility on arranging Regions, Blocks and Fields.

# Answer
> 0 votes
You can do ist with panels module

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