# Question
Title: Issue a html.tpl.php override from a module?
Is there a way to override the output of a page from a contributed module and issue your own html.tpl.php, effectively taking control of the output from the theme?

I want to do this in effort to create a unique login/registration experience, but can only seem to override the page level template, not the html level template. I see that the print module kind of does this, but is that the way to approach it?

# Answer
> 4 votes
According to this answer, you could simply print the page content in the menu page callback rather than returning it.

> To get data from Drupal's database and/or produced in PHP, you need a page callback (in a custom module) that output the data without the full layout rendering. This is easily doable by printing the content of the page directly in your page callback instead of returning it.

I guess the Print module implemented the printer-friendly page in this way. The following is the code snippet from the module.

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

  $items[PRINT_PATH] = array(
    'title' => 'Printer-friendly',
    'page callback' => 'print_controller_html',
    'access arguments' => array('access print'),
    'type' => MENU_CALLBACK,
    'file' => 'print.pages.inc',
  );
  ........
}

/**
 * Generate an HTML version of the printer-friendly page
 *
 * @see print_controller()
 */
function print_controller_html() {
  $args = func_get_args();
  $path = filter_xss(implode('/', $args));
  $cid = isset($_GET['comment']) ? (int)$_GET['comment'] : NULL;

  // Handle the query
  $query = $_GET;
  unset($query['q']);

  $print = print_controller($path, $query, $cid, PRINT_HTML_FORMAT);
  if ($print !== FALSE) {
    $node = $print['node'];
    $html = theme('print', array('print' => $print, 'type' => PRINT_HTML_FORMAT, 'node' => $node));
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    drupal_send_headers();
    print $html;
    ......
}

```

According to this, the module uses the custom HTML template `print.tpl.php`. It is a HTML-level template. The module then gets the HTML by calling `theme('print',...)` and render it directly to the browser using `print $html;`.

Here is a general idea for your purpose: **mymodule.module**

```
/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['mylogin'] = array(
    'title' => 'Custom Login Page',
    'page callback' => 'mymodule_custom_login_page',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mylogin' => array(
      'variables' => array('page' => array()),
      'template' => 'mylogin', // mylogin.tpl.php in your module folder
    ),
  );
}
/**
 * Generate a custom login page
 * @see more in print_controller_html() in print.pages.inc of the Print module
 */
function mymodule_custom_login_page(){
    $page = _mymodule_login_page_prerequisite(); // get/prepare necessary variables, js, css for the page
    $page['form'] = drupal_render(drupal_get_form('user_login')); // get login form
    // prepare html in mylogin.tpl.php
    // See more in print.tpl.php() in the Print module
    $html = theme('mylogin', array('page' => $page));

    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    drupal_send_headers();
    print $html; // cease Drupal page rendering and render directly to the browser
}
/**
 * Prepare the array for the template with common details
 * @see more _print_var_generator() in print.pages.inc of the Print module
 */
function _mymodule_login_page_prerequisite(){
    global $base_url, $language;
    $page = array();
    $page['language']   = $language->language;
    $page['head']       = drupal_get_html_head();
    $page['title']      = '';
    $page['scripts']    = drupal_get_js();
    $page['favicon']    = '';
    // if there is a custom css file for this page
    // drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/mylogin.css');
    $page['css'] = drupal_get_css();
    $page['message'] = drupal_get_messages();
    $page['footer_scripts'] = drupal_get_js('footer');

    return $page;
}

```

Template: **mylogin.tpl.php**

```
<?php
/**
 * @file
 * Custom login page template
 *
 * @ingroup page
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php print $page['language']; ?>" xml:lang="<?php print $page['language']; ?>">
  <head>
    <?php print $page['head']; ?>
    <title><?php print $page['title']; ?></title>
    <?php print $page['scripts']; ?>
    <?php print $page['favicon']; ?>
    <?php print $page['css']; ?>
  </head>
  <body>
    <h3>This is custom login page.</h3>
    <?php
    if (!empty($page['message'])):
        foreach($page['message'] as $type => $message):
        ?>
            <div class="messages <?php print $type; ?>">
                <ul>
                <?php foreach($message as $msg): ?>
                    <li><?php print $msg; ?></li>
                <?php endforeach; ?>
                </ul>
            </div>
        <?php
        endforeach;
    endif; ?>
    <div><?php print $page['form']; ?></div>
    <?php print $page['footer_scripts']; ?>
  </body>
</html>

```

I hope this will customize your login page as you need.

# Answer
> 2 votes
Both @Sithu and @Ayesh K have provided great answers. In this example, I will combine @Ayesh's method and parts of @Sithu's code for a complete solution.

hooks\_menu or hook\_menu\_alter functions both provide a `delivery callback`, which instruct Drupal on how you want your code wrapped. By default, Drupal sets `delivery callback` to drupal\_deliver\_html\_page(), which roughly tells Drupal to wrap your page in `html.tpl.php` and `page.tpl.php`.

To modify the way Drupal wraps your page, copy the function `drupal_deliver_html_page()` into your module, and modify it. Then call your new function in `delivery callback`. Drupal will then use that function to wrap your page.

# Example

Here's a working module. Place the following code into your `/sites/all/modules/MYMODULE` directory and enable the module.

Optionally, to override an existing path, substitute `hook_menu` with `hook_menu_alter`.

**MYMODULE.module**

```
<?php
function MYMODULE_menu() {
  $items['login'] = array(
    'title' => 'Login',
    'page callback' => 'MYMODULE_page',
    'delivery callback' => 'MYMODULE_deliver',
    'access callback' => TRUE,
  );
  return $items;
}

function MYMODULE_page() {
  global $user;
  if (!$user->uid) return drupal_get_form('user_login'); // Show login for guests.
  else drupal_goto('user/' . $user->uid); // Redirect members to own profile.
}

// Code taken from drupal_deliver_html_page().
function MYMODULE_deliver($page_callback_result) {
  global $language, $base_path;
  // Pass variables to the template.
  $vars = array(
    'language' => $language->language,
    'title' => 'My Custom Login',
    'favicon' => '',
    'css' => $base_path . drupal_get_path('module', 'MYMODULE') . '/MYMODULE.css',
    'messages' => theme_status_messages(array('display' => NULL)),
    'content' => drupal_render($page_callback_result),
  );
  echo theme('MYMODULE_login', array('vars' => $vars)); // Uses template defined in hook_theme().
  drupal_page_footer();
}

function MYMODULE_theme() {
  $items['MYMODULE_login'] = array(
    'template' => 'MYMODULE',
    'render element' => 'page',
  );
  return $items;
}

```

**MYMODULE.info**

```
name = MYMODULE
description = "Module description."
package = Custom
core = 7.x

```

**MYMODULE.tpl.php**

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $vars['language']; ?>" version="XHTML+RDFa 1.0">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title><?php print $vars['title']; ?></title>
  <?php print $vars['favicon']; ?>
  <link rel="stylesheet" type="text/css" href="<?php print $vars['css']; ?>">
</head>
<body>
  <?php echo $vars['messages']; ?>
  <div class="content">
    <?php print $vars['content']; ?>
  </div>
</body>
</html>

```

**MYMODULE.css**

```
.content { color: pink; }

```

# Answer
> 1 votes
I think you need to invest some time finding the most appropriate hook for this. You can try

* hook\_page\_alter to change "what is going to be rendered",
* use hook\_menu\_alter to change the delivery callback for login and register menu routers,
* use a page--user-login.tpl.php file to take over the page template of the login page,
* add some template suggestions in template.php to use a different html.tpl.php file just for the login paths,
* or finally, hook\_theme\_regitry\_alter, to alter the theme registry and do what you wanted to do (the html.tpl.php change)

---
Tags: 7, theming
---


# Question
Title: Populate dropdown with data from database in Drupal7 using jQuery
Error is seen when i made a drop down list to populate data from Database.
Database : dtable
File in the template of hook\_theme named : **myModueForm\_theme.tpl.php**

```
<?php
$sel = "<select  name=\"select1\" id=\"select1\">
        <option value=\"\">Select...</option>
        <option value=\"data1\">data1</option>
        <option value=\"data2\">data2</option>
        <option value=\"data3\">data3</option>
        <option value=\"data4\">data4</option>
    </select>";
echo "$sel";

```

?\>

**Script :**

```
jQuery("#select1").change( function(){
if( jQuery(this).val() == "data1" ) {
jQuery.ajax({
    type: "POST",
    url: "<?php echo $base_url;?>?q=search/data1",
    error: function(returnval) {
        alert("Failure");
    },
    success: function (returnval) {
        alert(returnval);
        alert("Sucess");
    }
})
}
});

```

The Module file which handles the database connection named: **myModule.module**

```
$items['search/data1'] = array()
'title' => 'Add data', //page title
'description' => 'form',
'page callback' => 'search_data1',
'page arguments' => array('access content'),
'access callback' => TRUE

```

);

// In the search\_data function

```
function search_data1(){

$options="<select  name=\"select2\" id=\"select2\">";
$result = db_select('dtable', 'c')
    ->fields('c')
    ->execute()
    ->fetchAll();
foreach ($result as $record) {
$name = ($record->dt1);
    $options.="<option value=\"$name\">".$name."</option>";
    //alert(node);

}
$options.= "</SELECT>";
return $options;

```

}

What I want is

* please tell me where is the error & how to solve
* I want to return the page back to the theme PHP page with the query result, but when I display back the return value from the module file, I get the whole HTML.

Please help & treat me as a beginner.Thanks in advance...

# Answer
By default, hook\_menu's `delivery callback` is set to drupal\_deliver\_html\_page(), therefore it delivers content wrapped in a page template. You will need to modify the `delivery callback`.

# To output page content in ajax

```
function MYMODULE_menu() {
  $items['search/data1'] = array()
  'title' => 'Add data', //page title
  'description' => 'form',
  'page callback' => 'search_data1',
  'page arguments' => array('access content'),
  'delivery callback' => 'MYMODULE_ajax_deliver',
  'access callback' => TRUE
}

function MYMODULE_ajax_deliver() {
  if ($page_callback_result) echo drupal_json_output($page_callback_result);
}

```

# To output naked page content

```
function MYMODULE_menu() {
  $items['search/data1'] = array()
  'title' => 'Add data', //page title
  'description' => 'form',
  'page callback' => 'search_data1',
  'page arguments' => array('access content'),
  'delivery callback' => 'MYMODULE_custom_deliver',
  'access callback' => TRUE
}

function MYMODULE_custom_deliver($page_callback_result) {
  if ($page_callback_result) echo $page_callback_result;
}

```

To learn more about a custom `delivery callback` function, see my other answer.
> 1 votes

---
Tags: database, javascript
---


# Question
Title: Fatal error: Unsupported operand types in form.inc
I'm getting the following error message:

> Fatal error: Unsupported operand types in /var/www/public\_html/domain.com/includes/form.inc on line 1079

It seems to be because the following code for an admin menu.

```
function MY_MODULE_admin_menu() {
  $menu_items = db_query("SELECT * FROM my_module")->fetchAll();
  $header = array('Template ID', 'Name', 'Type', 'Template');
  $rows = array();
  if (!empty($menu_items)) {
    foreach ($menu_items as $menu_item) {
      $rows[] = array($menu_item->tid, $menu_item->name, $menu_item->type, $menu_item->template);
    }
  }
  return theme_table(array(
    "header" => $header,
    "rows" => $rows,
    "attributes" => array(),
    "sticky" => true,
    "caption" => "",
    "colgroups" => array(),
    "empty" => t("Table has no rows"),
      )
  );
}

```

What's causing this? As far as I can tell, this is how it is supposed to look for Drupal 7.

# Answer
Duplicate of this question:

Db\_Query Fatal error: Unsupported operand types

It turns out that I was setting my page callback to a drupal\_get\_form with no form present.

I changed my hook\_menu to:

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

  $items['admin/structure/module'] = array(
    'title' => 'description of module',
    'description' => 'Configure settings for module',
    'page callback' => 'MY_MODULE_admin_menu',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

```

And it worked fine.
> 0 votes

---
Tags: 7, routes
---


title: Check if user is online

text:
# Question
Title: Check if user is online
I need to display an image when a user is online. Like the button of skype that it say if the user is online on skype's system.

How can I "check" if a user is online ? Is there a light module or I need to create a new one ? I don't need any type of block o stats about this user, only know if he is online or not.

Thanks.

# Answer
> 4 votes
For readability, and simplicity, I like to use the core API:

## Check if current user is authenticated

user\_is\_logged\_in()

i.e:

```
if (user_is_logged_in()) {
  // User is authenticated
  print $content;
}

```

You can also use

```
if (!user_is_logged_in()) {
  // User is anonymous
  print $content;
}

```

though there's even a user\_is\_anonymous() function

```
if (user_is_anonymous()) {
  // User is anonymous
  print $content;
}

```

## Check if particular user is logged in

If you want to check if a particular user is online

You can use Rules, or hook\_user\_login to respond to login event

```
EXAMPLE_user_login(&$edit, $account){
  /* do stuff */
}

```

or query the session table for that user session uid

```
// Check if user $uid is online in the last 10 minutes
$online = db_query("SELECT uid FROM {sessions} WHERE uid = :uid AND timestamp >= :time", array(':uid' => $uid, ':time' => (REQUEST_TIME - 600)))->fetchField();

```

# Answer
> 2 votes
If you want to show an image for each logged-in user, then you can use code similar to the one used for the block showing the list of currently logged-in users. For Drupal 7, the code would be similar to the following one.

```
function mymodule_logged_in_users($delay = 900, $max_users = 10) {
  $items = array();
  $interval = REQUEST_TIME - $delay;

  // Perform database queries to gather online user lists. We use s.timestamp
  // rather than u.access because it is much faster.
  $authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();

  if ($authenticated_count) {
    $items = db_query_range('SELECT u.uid, u.name, MAX(s.timestamp) AS max_timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= :interval AND s.uid > 0 GROUP BY u.uid, u.name ORDER BY max_timestamp DESC', 0, $max_users, array(':interval' => $interval))->fetchAll();
  }

  return $items;
}

```

`$items` contains the list of users who are logged-in in the specified interval.

# Answer
> 1 votes
This function is based on the code given by kiamlaluno. I needed a simple way to check if a user is online given the user id. Below is the code that worked for me.

```
function user_is_online($uid, $delay = 900) {

  $interval = REQUEST_TIME - $delay;
  $ret = db_query('SELECT
    u.uid,
    MAX(s.timestamp) AS max_timestamp
    FROM {users} u
    INNER JOIN {sessions} s ON u.uid = s.uid
    WHERE s.timestamp >= :interval
    AND u.uid = :uid
    GROUP BY u.uid', array(':interval' => $interval, ':uid' => $uid))->fetchAll();

  if(count($ret)) return TRUE;

  return FALSE;

}

```

# Answer
> 0 votes
You can add to your template file the next check:

```
global $user;
if ($user->uid)
{
    print "User Online";
}

```

---
Tags: 7
---


# Question
Title: Dynamically filling up fields of a node in Drupal
We have a content type named "Person", which has fields as Full Name, Age, Address etc.

There are thousands of people entries on the site. We are using Views to sort out people's list on different pages as per need.

Lately, there has been a requirement that we need to sort the list of people by Last Name. But the problem is that there's no last name field as there's only "Full Name" field of the person in the site.

I am using views to sort the results in the pages and I am not sure how to sort the results by last name. Is there any way I can achieve this?

May be I can create a field as "Last Name" in the content field but is there a way I can dynamically fill in the Last Name by extracting Last word from Full Name?

May be through someway in SQL?

Any idea or assistance would be highly appreciated.

Thanks.

# Answer
Here is my way of doing it:

* Create a Computed Field to manipulate the substring (Last Name) and store it as a field

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code.

> The Computed Field module only updates its computed values on saves or on load (if no computed value is computed yet). This is not optimal when using computed values in lists etc., or if you should wish to change the logic in the computed field.

* Use this *Computed Field* as a *sort criteria* in Views.
> 2 votes

# Answer
You can create a user defined function for this

With that function, you would be able to build your query as follows:

```
SELECT SPLIT_STR(fullname, ' ', 1) as fullfirst,
       SPLIT_STR(fullname, ' ', 2) as fulllast
FROM   users;

```

You can also do the following:

```
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) as fullfirst,
       SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) as fulllast
FROM   users;

```
> 1 votes

---
Tags: entities, database
---


title: Using Webform to create a node

text:
# Question
Title: Using Webform to create a node
So i know there are answers around not using Webform, but i require the reporting and tracking functionality of webform, so please stick to using it.

I am needing to create a node based on a questionnaire that is filled out so i can then display the answers of each submission in a list view/ detailed view setup. they are stories that users are able to tell to the world then have displayed on the site.

Any ideas?

# Answer
> 3 votes
You should use Rules module in the following way:

1. Install and enable Rules module
2. Install and enable Webform Rules (https://drupal.org/project/webform\_rules)
3. Create a new rule
4. Choose the "After a webform has been submitted" event
5. Optionally set your conditions
6. Add a new action "Create a new entity" of type "Content"
7. Add the neededs action to add properties to the created entity
8. Add the save action

*Note:* You can use Tokens available with "Set a data value" .

---
Tags: webforms
---


title: How to create vocabulary page?

text:
# Question
Title: How to create vocabulary page?
I want want to create page for vocabulary. I mean not vocabulary term, but vocabulary name.

```
mysite.com/myvocab

```

rather than

```
mysite.com/myvocab/term

```

That page should also have possibility to display text (how can I add text field to vocabulary and not vocab term?)

Thanks!

# Answer
There is two simple way to do it I think :

1. Use Vocabulary module which gives you the taxonomy/vid page.
2. Or Use views to create your page. Create a taxonomy type view and add `Taxonomy vocabulary: Vocabulary ID` or `Taxonomy vocabulary: Machine Name` as argument.
3. If you want to display the nodes related to vocabulary then I think you need to use Views Field View with 2nd option.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Change text in Commerce Kickstart "order total" dynamically
I want to change the label in the attached image, that is from Commerce Kickstart. I need to change that text depending on the role of the user.

If the user has **role1** then the text will be "**order total**" & if user has **role2** then the text should change to "**Quote total**". Any idea?

I tried to debug with Devel to see where to change the label but I could not find it.

# Answer
> 2 votes
You can use the `hook_commerce_price_formatted_components_alter()` The following example checks if VAT has been applied to the order total and changes the string accordingly:

```
/**
 * Implements hook_commerce_price_formatted_components_alter().
 *
 * Alters somes text at the checkout form
 *
 * @param $components
 * @param $price
 * @param $entity
 */
function mymodule_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  $pieces = explode('/',current_path());
  if(!isset($components['tax|ch_vat']) && $pieces[0] == 'checkout'){
    $components['commerce_price_formatted_amount']['title'] = t('Order total (excluding VAT)');
  }
}

```

# Answer
> -1 votes
One way would be to implement `hook_entity_view_alter()` in a custom module of yours.

```
<?php
/**
 * Implements hook_entity_view_alter().
 */
function YOURMODULE_entity_view_alter(&$build, $type) {
  switch ($type) {
    case 'commerce_order':
      /**
       * In here implement your alter logic
       */
      break;
  }
}

```

To determine what exactly to alter, after the *'in here...'* comment you can use `debug($build);` or `dpm($build);` (if devel installed).

To see the user roles:

```
global $user;
debug($user->roles);

```

Similar issue here.

---
Tags: 7, commerce
---


title: Using computer's proxy settings

text:
# Question
Title: Using computer's proxy settings
Currently I'm manually putting my local environment proxy settings in my settings.php file like so:

```
 $conf['proxy_server'] = '192....';
 $conf['proxy_port'] = ####;
 $conf['proxy_username'] = 'myusername';
 $conf['proxy_password'] = 'mypassword';
 $conf['proxy_user_agent'] = '';
 $conf['proxy_exceptions'] = array('127.0.0.1', 'localhost');

```

This works, but I work with a team, and the others on my team can see my login info when they enter the settings.php file. Plus when I change my password, I need to remember to change it here.

We're using Windows 7 machines. How could I make it so that Drupal automatically uses the logged-in user's credentials (like the way browsers seem to do) instead of hard-coding them into the settings.php file?

# Answer
> 1 votes
Sharing settings.php isn't good practice at the best of times.

Instead, it would be better to make that file specific to your own machine, and exclude it from version control. Have the rest of your dev team do the same. Then the problem is mostly solved, and you'll find it impossible to accidentally overwrite a production site's settings.php as a bonus.

Regarding automatically updating when you change your password - I think you're out of luck.

The way `drupal_http_request()` uses the proxy vars means you need to provide URL, username and password in plaintext as variables (i.e. the `$conf` array). I may be wrong, but I don't think you can get at those system credentials through PHP. Perhaps there's an extension that provides it, but I haven't come across one before. I'm almost positive core PHP doesn't have anything useful anyway.

---
Tags: proxies
---


# Question
Title: how to theme the read more link using fields mode in views,
In views i have created a block view in where i want to list only the titles of 5 nodes, using the 'field' setting in views. Under 'pager' i have set the amount of items accordingly. I have enabled 'the read more' link in case more nodes show up.

My problem is that when my read more link shows up it is way out of line with the listing.(right side)

With my chrome element inspector i set the aligning of the read more link to left which is acceptable.

How can i accomplish this with in my drupal set up.

Help appreciated.

# Answer
You should be making any theme changes in a sub theme, rather than editing the actual theme files. This is so all of your changes are not wiped out when an update is available for corporate clean.

Please read https://www.drupal.org/node/225125 for more information on sub theming.

As for the changes to be made to your stylesheet, open your style.css in an editor such as notepad++ and add the following lines (if align left is what you need)

```
.more-link {
  text-align:left;
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Webform does not submit when a file field is added
I have a single page webform with a bunch of fields (text field, radio buttons, etc) that works fine. As soon as I add a file upload field it stops working:

* when submitted, the form returns with all the fields still filled in
* there are no validation messages of any kind

I've littered webform.module with lines of print statements and it appears that `webform_client_form_validate` and `webform_client_form_submit` are never called at all. I suspect some module may be altering my form because it picks up the file field somehow.

All webform related modules have been disabled.

I suspect I'm having a similar problem this question describes: Webform does not submit, instead redirects to self . The suggested solutions are rather vague though, and I'm not sure how to proceed.

# Answer
> -1 votes
I discovered the issue: I had added a script to my theme to prevent double form submissions: a simple "if the submit button is clicked, disable submit buttons in the form" jquery script.

This script prevented the submit button of the field field from being activated at the same time the main submit button was pressed. This confused Drupal to a sufficient degree that nothing worked anymore.

I fixed it by wrapping the disabling of submit buttons in a window.setTimeout(function yada yada ... , 50).

---
Tags: 7, webforms
---


# Question
Title: record of email notifications sent out (webform / postfix)
I have a webform with example.com/node/123/webform/emails set to send email notification from info@example.com to several email addresses when a submission is received.

Is there a way to see a record of email notifications sent out ie with date and time etc to verify that the notifications have in fact been sent?

Thanks...

# Answer
My favorite and so far most reliable, if not most convenient, way to achieve that is out of Drupal, actually. If you set it up inside Drupal, and you hit some errors, you never are 100% certain if mail wasn't sent, or just wasn't logged. Or, if logging happens first, you can never know for sure if mail was sent, or was only supposed to be.

The way I prefer to do it is to use external SMTP server for outgoing mail. That way I can be sure all mail I have logged actually was sent from Drupal, and chance I logged all mail are bigger, too. After all, SMTP servers have decades of evolution more than Drupal, or even PHP. Added bonuses include:

* Less CPU and memory use on webserver, because it does not need code for mail log, and this code would be loaded on each uncached request.
* Ability to deliver mail even if recipient's server is temporarily down.

# Example

If you have business Gmail, you can use SMTP Authentication Support module to make your site send via Gmail, and you will see mail sent from site in your Sent Mail, just like this:

No special configuration was needed to get this working. You can use full power of Google if you do so: filters, labels, whatever you wish.

If you will use company mail server, just make sure your sysadmin will configure it in similar manner.
> 0 votes

# Answer
Webform doesn't provide default functionality for it.

you can use either of these modules to log outgoing mail:
> 2 votes

---
Tags: webforms, emails
---


# Question
Title: grouping nodes with collapsible fieldset
I use `entityreference` to link nodes to other nodes and `field_group` to display collapsible fieldsets with fields.

Assume I have node#1 which has a field `related_nodes` containing node#2, node#3 and node#4.

The display of this node looks like this:

```
node title

node body

related:
- node#2
- node#3
- node#4

```

I can use `hook_node_view` to remove nodes from the `related_nodes` field on the fly using something like:

```
unset($node->content['field_info_case_law_references']['#items'][?]);

```

I want to remove all those nodes (e.g based on their title) and place them in groups, each in a collapsible fieldset within that `related:` field. so it ends up looking something like this:

```
node title

node body

related:
+ starting with A (collapsible fieldset)
  - node#2
+ starting with B (collapsible fieldset)
  - node#3
  - node#4

```

The default collapsible behaviour, html and styling of that I can configure from `admin/structure/types/manage/*/display` is good enough.

Where should I look at?

# Answer
> 0 votes
OK I found it.

In the `HOOK_node_view` I can do:

```
if ($node->type=='CONTENT_TYPE') {

  // clone from a fieldset nearby
  $node->content['#fieldgroups']['group_FOO']=clone $node->content['#fieldgroups']['group_ORIG'];

  // modify fieldset
  $node->content['#fieldgroups']['group_FOO']->label="xxxxxxxxxxxxxxxxxxxxxxxx";
  $node->content['#fieldgroups']['group_FOO']->weight=-1;
  $node->content['#fieldgroups']['group_FOO']->identifier=...
  $node->content['#fieldgroups']['group_FOO']->group_name=...

  // clone from a field nearby
  $node->content['field_FOO'] = $node->content['field_ORIG'];

  // modify field
  unset($node->content['field_FOO']['#items'][0]);
  unset($node->content['field_FOO']['#items'][1]);
  unset($node->content['field_FOO']['#items'][2]);

  // position fieldset and field
  $node->content['#group_children']['group_FOO'] = 'group_ORIG';
  $node->content['#group_children']['field_FOO'] = 'group_FOO';

}

```

---
Tags: nodes, entities
---


# Question
Title: Incomplete Object error when updating site (after Drupal timeout)
I (foolishly) tried to enable an installed module whilst on my shared hosting. The site times out, which isn't all together unsurprising. However now I get this error message whenever I try and make any updates to the site (enable any modules, clear cache, run cron etc.)

Any thoughts as to the cause. Here is the error in full.

> Fatal error: views\_plugin\_display::destroy(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "metatag\_views\_plugin\_display\_extender\_metatags" of the object you are trying to operate on was loaded *before* unserialize() gets called or provide a \__autoload() function to load the class definition in /home/xxxxx/public\_html/sites/all/modules/views/plugins/views\_plugin\_display.inc on line 272

If it makes any difference it was the Metatag module I was trying to enable.

# Answer
I had this error when running update after disabling Metatag and Metatag: Views. It went away when I re-enabled those two modules.

That also seems to have fixed some other issues I was having with the modules form; it would white screen on me after disabling (certain?) modules, although I could return to the Admin interface.
> 1 votes

# Answer
I had this issue when disabling Metatag: Views and everything get back to work smoothly enabling again. The problems seems to be related to this issue: https://www.drupal.org/node/1278534
> 1 votes

---
Tags: 7
---


# Question
Title: User profile image update from a popup window
Is there a way to make the user profile image updated using overlay window from different page other than /user/edit

# Answer
> 1 votes
Profile Pic Changer Module Provides a modal dialog box to change user pictures

> Allow users to change their profile picture through a modal form directly on their profile page, without having to go to the profile edit form.

---
Tags: 7, media, users, modal-dialogs
---


title: Translating Views Pager

text:
# Question
Title: Translating Views Pager
Help, how to translate paginator in views? In my views I used a mini pager with tags backwards/forwards. Tried to do through translate interface, but nothing happened.

# Answer
After Installing i18nviews Module, You should check *admin/config/regional/translate/translate* where you should search for the string

Here is a discussion going about it : Views pager translation not working
> 1 votes

---
Tags: 7, views, i18n-l10n, paging
---


# Question
Title: Track how many times a JSON file is requested from other websites
I developed a mobile site using html and angularjs, which displays all of data from my Drupal site. From a view that output JSON data. All data collect good from JSON, but i can't create a popular item list.

Since, drupal not update node view by json request. So, i think, if i collect total request of each json/view, i can filter by this from my mobile site. So, i need to display how many times this json/view is requested from other domain/website like **statistics** module.

Does any method to track how many times a specific JSON/VIEW is called or requested from another domain/website?

# Answer
> 0 votes
There is a core module for that Statistics. On the configuration of this module (admin/config/system/statistics) you can ask for 'Count content views' who should work on every page drupal display (so your json).

There are a lot of custom module to extends statistics.

A little warning : Angular may be cache your json, so if your user go two times on a page you can loose this data. Maybe smarter to do this on the angular side.

---
Tags: views, 7
---


# Question
Title: Generating internal URL/redirect by path>
In the past I could set up redirects with `drupal_goto` using a simple path (i.e., node/1).

Is this not possible at all in Drupal 8? Everything I've seen relies on a route name but that requires either generating a page in a module or keeping a static note of a node id, which seems backwards.

If I use Url::fromUri(), I can't seem to use getRouteName() since it interprets that as an external URL (even though the domain is the Drupal install).

What is the best way to get the route name of an internal path?

# Answer
drupal\_goto is removed in favor of RedirectResponse (record).

> As of Drupal 8 drupal\_goto() has been removed in favor of RedirectResponse which comes together with the Symfony HttpFoundation.
>
> hook\_drupal\_goto\_alter() was also removed as well, in favor of just using an event listener on kernel.response

**Drupal 7**

```
<?php
function my_menu_callback_foo() {
  //....
  drupal_goto('user');
}
?>

```

**Drupal 8 (procedural)**

```
<?php
function my_menu_callback_foo() {
  $url = Url::createFromPath('node/1');
  return new RedirectResponse($url->toString());
 //Or try this:
 return new RedirectResponse('node/1');
}
?>

```
> 2 votes

---
Tags: 8
---


# Question
Title: Entity Reference field using View to Mask Autocomplete with Last Name
I've posted about this here as well: http://drupal.org/node/1906344

I'm trying to use an Entity Reference field to reference users with a last name field I created on a "Product Page" content type.

You see, whenever you try to reference a user, you're forced to do so with the username. So to get around this, you have to create a view that outputs the last name field from the profile and then use that view in a way that accepts an argument to key off of (i.e. - the last name).

I've created my view and on the views page, this view works. But when I use the "Filter by an entity reference view" to attach my view, I discover that it doesn't work on the node-add page. I'll start typing a last name that's associated with a registered user and, well, nothing comes up. The reference type I indicated in the "Target type" is user and the view isn't anything special: it's just an "Entity Reference" view type set to accept 1 contextual filter (the last name) and subsequently outputs the respective users if that argument matches the last name field value(s). So I don't know what's going on here...

Here's my basic setup: \- Drupal 7.x \- Entity API 7.x-1.0 \- Entity Connect 7.x-1.0-beta2 \- Entity Reference 7.x-1.0 \- Views 7.x-3.5

I'm using Entity Connect to provide the ability to create the user if he or she doesn't exist. Otherwise, the field *should* reference something--which it currently doesn't.

Any help on this is appreciated and please let me know if you need more information.

# Answer
> 1 votes
Remove the contextual filter from your Entity Reference view.

The view should have **all** the available options. The autocomplete widget for the Entity Reference field will filter the available options based on the user input. If you change the widget type to "Check boxes/radio buttons" you can see the available options which may help diagnose the issue.

---
Tags: entities
---


# Question
Title: What are valid entity_id and entity_type values for node content?
I'm trying to track down some performance issues on a Drupal 7 site where out of nowhere the site will stall rendering content or dealing with administrative duties like updating a piece of content. Checking the logs, I've found errors when cron runs for:

* EntityMalformedException: Missing bundle property on entity of type node
* Notice: Undefined property: stdClass::$nid in node\_build\_content()
* Notice: Trying to get property of non-object in \_node\_index\_node()

This prompted me to create a view to look at all content types and return

* title,
* node\_id,
* entity\_id
* entity\_type

This view shows the majority of site content has entity\_id = 0 and entity\_type = null (nothing).

Out of roughly 400 nodes, less than 20 have proper entity\_types and entity\_id values. Even creating a simple basic page with a title and body results in entity\_id = 0 and no value for the entity\_type.

You would think that the content wouldn't render however, all of this content will render at /node/xxx or pulled up in views and can be edited as usual.

I think this is one of the causes of the poor performance if not the cause so I'm looking to repair the broken nodes and and prevent this site from continuing this odd behavior. I'm pretty sure the entity\_id should equal node\_id and I'm pretty sure the entity\_type should equal node.

Drupal 7.34

# Answer
> 1 votes
This error can be caused by having a term reference field that references a deleted term. This reference is not deleted when a term is deleted.

You can check if this is the case using this query

```
SELECT nid, title from node WHERE nid
   IN (select entity_id from  field_data_field_some_ref
   WHERE field_some_ref_tid not IN (select tid from taxonomy_term_data))

```

https://www.drupal.org/node/1778572#comment-7256200

There are other cases where this error can occur. Read the issue comments in the link for more info.

---
Tags: nodes, entities
---


# Question
Title: How do we configure SElinux to not break Drupal?
I've installed Drupal on Red Hat 7 in Amazon Web Services, using a database on a separate RDS instance.

My original problem was that I couldn't make the Drupal installer recognize the /sites/default/ or /sites/default/files directories as writable, even after I confirmed they were writable by the ''apache'' user or temporarily set the permissions to writable by all. (This year-old issue may be similar.) When I filled in settings.php myself, then Drupal gave this connection error:

> PDOException: SQLSTATE\[HY000\] \[2003\] Can't connect to MySQL server on 'my-database-endpoint.rds.amazonaws.com' (13) in lock\_may\_be\_available() (line 167 of /var/www/html/includes/lock.inc).

Disabling SElinux allows the installer to finish and allows Drupal to work. Re-enabling SElinux ('''setenforce 1''') stopped the installer; re-enabling SElinux after installation breaks Drupal, resulting in the same connection error given above. Drupal.org mentions the problem, but doesn't give a specific solution for this case.

I figure many other people must have run into the same problem when installing Drupal.

Obviously I have to re-enable SElinux, so does anyone already know how to modify SElinux configurations to enable Drupal to work properly (and not degrade security)?

# Answer
Looks like you are connecting to a remote host. You may need to allow httpd to make remote connections. Run these commands as root to set the SELinux variables.

```
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1

```

http://alexbilbie.com/2013/02/selinux-php-mysql/
> 2 votes

---
Tags: installation, files, database
---


# Question
Title: SEO friendly URL for drupal commerce products
I am using Commerce Product Url module for generating unique url for commerce products like follows,

For each product it provides id parameter,

* mycommercesite.com/node/1?id=1
* mycommercesite.com/node/1?id=2

as well as sku parameter,

* mycommercesite.com/node/1?sku=pr1
* mycommercesite.com/node/1?sku=pr2

But *I need SEO friendly URL for each product*

for example,

* **mycommercesite.com/node/1/product1**
* **mycommercesite.com/node/1/product2**

Is there any way to do this?

Thanks.

# Answer
> 0 votes
the module Commerce product Url is for make unic urls based on product variations, it means when you have one product display showing different product variations.

Check this issue where they explain a little bit better what Im telling you

But there is a non-drupal solution to convert dinamic urls into SEO-friendly urls, that is using mod\_rewrite:

EXAMPLE

Sad Original URL = site.com/node/1?id=54

Happy URL :) = site.com/node/1/rueben-sandwich/

Use mod\_rewrite in your .htaccess file to parse out the elements of the URL. Like this:

```
RewriteEngine On //check that in drupal's .htaccess the rewrite engine is on by default

RewriteRule /(.*)/$ node/.*$?id=$1

```

the `(.*)` pulls the element out and puts it in variable $1. and the `.*$` is just a wildcard that accepts everything after node/

Try it and tell us if it worked because I have not tried it with Drupal websites.

by the way, try to use sku, or some other argument in the url through the module configs, so your url would look better because using "id" the final result of the above code would be /node/1/54

---
Tags: commerce
---


# Question
Title: Drush command using chef causing error "Command needs a higher bootstrap level to run"
Expected process to exit with \[0\], but received '1'

```
---- Begin output of /usr/local/drush/drush -y en views ----
STDOUT:
STDERR: Command pm-enable needs a higher bootstrap level to run - you will   [error]
need invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en views' could not be executed.                  [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This error often occurs when Drush is trying to bootstrap a
site that has not been installed or does not have a configured
database.

```

Please note that database and executing command lines are having full privileges.

# Answer
> 0 votes
In your drush command you may need to specify the location of your Drupal files. Use `--root=<path>` argument.

https://github.com/drush-ops/drush#options

---
Tags: drush
---


title: jQuery ui isn't loading

text:
# Question
Title: jQuery ui isn't loading
I'm simply trying to implement the tabs widget on a particular page.

* I have both `jquery_update` and `jquery_plugins` modules enabled.
* If I go to `Administration > Reports > Status report` Under jQuery Update, I see `jQuery 1.10.2 and jQuery UI 1.10.2` are both green and showing as loaded.
* If I type `jQuery.fn.jquery` into the console I see `"1.10.2"`

But the bad news is

* If I try to use `jQuery("#tabs").tabs();` I get an `Uncaught TypeError: undefined is not a function` error
* If I enter any of the following "jQuery.fn.ui","jQuery.ui", "$.fn.ui", "$.ui" into the console: I get `undefined`
* Having this in my `template.php`:

:

```
 function my_theme_preprocess_page(&$vars){
   drupal_add_library('jquery_plugin', 'tabs.min.js');
 }

```

does nothing.

* And finally, checking the heading of the rendered page, I see a call to Google CDN to the minified version of jQuery 1.10.2, but don't see any similar call to grab the jQuery UI library.

Working with Drupal and jQuery is such a nightmare, what else can I check, do, change, to get this working?

# Answer
In your theme\_preprocess\_page function use this

```
drupal_add_library('system', 'ui.tabs');

```

Here is a list of all the libraries for 'system' https://api.drupal.org/api/drupal/modules%21system%21system.module/function/system\_library/7
> 1 votes

---
Tags: javascript
---


title: External RSS Feed in View

text:
# Question
Title: External RSS Feed in View
I am looking for a module or way to use an external RSS feed in a view. I know this was easily done in Drupal 6, but I can't seem to find much on Drupal 7.

I am trying to use Views RSS, but there is very limited documentation.

# Answer
The simplest method is to use the Aggregator module included in core.

1. Enable the 'aggregator' module in core
2. Add your RSS feed in Configuration \> Web services \> Feed aggregator
3. On the same page, click 'update items' for your feed to retrieve the RSS feed and parse the items
4. Create a view that will show 'Aggregator items'
5. (Optional step for multiple feeds) Add a filter criteria for 'Aggregator feed: Title' to only show items from the specified feed

To do more advanced functionality you will need to use the Feeds module from contrib. That module will parse the fields from a feed into content nodes.
> 3 votes

# Answer
One of the sites I manage takes an RSS feed from a Ruby site and displays the content on our Drupal site via Views. To do this we use Feeds, which imports the RSS and then they are just normal nodes you can use in the view.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: Adding a button above rendered output from a contrib module
What I'm trying to do is add a button above some content that's being outputted by a contrib module (Search Api Saved Searches) .

Can I do this with hook\_page\_alter, if so how can I add this new render to the $page\[content\]\[system\_main\] . If not what hook would be best to solve my problem.

Many thanks.

# Answer
> 0 votes
If you are already using Display Suite or would like to use it, there is an area to create custom fields and display them within your node. You can use tokens and html.

Here is a good video.

---
Tags: theming
---


# Question
Title: How can pass a data of a node's field to entityform field
I have a field named "code". This hidden field stores some alfa\_numeric values.

Nodes with using this data field have an entityform type as a block in page.

How can I pass node's data values to entityforms data field as prepopulated.

# Answer
You can use hook\_form\_alter in a custom module and pass the node field value to the value of the form item eg :

```
<?php
  function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id){
    // dpm($form);
    $node = node_load(arg(1));
    $form['field_code']['#value'] = $node->my_field[LANGUAGE_NONE][0]['value'];
  }
?>

```

Things you need to know are:

The ID of the entity form for `FORM_ID`, you can get this using Get form ID module.

What the field you are populating is ? you can install Devel module then uncomment the line in the above code to inspect the form.

Where within the node object the field with the data is ? If Devel is installed you can navigate to the node and click on the Devel tab and explore the node there.

If you are using hidden fields then `['#value']` is ok but if it is a textfield then you should use `['#default_value']`.

Also, this is presuming that the form is in a block on the node page, other wise `node_load(arg(1));` will node work.
> 0 votes

---
Tags: forms, tokens, entities
---


# Question
Title: What are the implications of changing the default language?
On the official docs about Install a language there is a warning:

> Never change the default language, otherwise things will break!

I wonder what exactly this means because there is no explanation about it. I have searched and only found this.

I changed the default language and updated the translations about two weeks ago and haven't seen any warning or error yet but I'm still looking for some documentation since the site is going on production.

# Answer
> 2 votes
The main problem used to be i18n and all the things that it translates.

Most of those (like taxonomy terms, fields, node types, menus), do not have an explicitly language assignment like nodes do. So the original strings are assumed to be in the default language (unlike interface strings, where the original is always en).

If the old default language was english and you change it to german, then i18n will no longer translate them to german on the german site but will try to translate them from english to english.

i18n added a workaround for this problem, on one of the many settings pages can be controlled if a different language than the default should be used as that original language. That's not a perfect solution, because it means that the site admins must create the original fields, node types, menu links and terms (assuming that i18n\_string is used to translate them) in english and then translate them to german.

---
Tags: i18n-l10n
---


# Question
Title: Migration: Combine Profile2 and file migration
I need to migrate profiles from an external database (not drupal) to Drupal 7. The target system uses Profile2 profiles. I already wrote the migration of all the "primitive" fields with the help of this cookbook, but I'm stuck with the profile images. They are only accessible via url (blah.org/blah/\[user\_id\].jpg, so the migration needs to download them, and store them into a Profile2 profile field with type image. I know there is MigrateDestinationFile, but I dont see how to make the file\<-\>image\<-\>Profile2\_field connection.

Has anyone done that before?

# Answer
> 1 votes
This is not a complete working example but is still more an answer than a comment.

I'm assuming you're familiar with migration code in general.

I also assume you are using Migrate extras, which provides profile 2 support and has an example of a profile2 migration.

Because files are a separate entity from profiles you have to first have a file migration, which migrates the files into Drupal. In that linked example the first part of code is the file import and the second part is the node import that then uses those files in a file field. In your case the second part will be very similar but will be in your profile2 migration.

I haven't actually done an import that pulls in images from the web like this so this is an assumption. I would say set your source directory for your file import to the directory that you intend to download the remote files into. You can specify your directory like this and make it anywhere on your server: `'source_dir' => '/var/www/my-downloaded-files',`

Then after that you import your profile2 profiles.

Unfortunately I have only done file migrations from Drupal to Drupal so I'm not sure off the top of my head what you specify for the source field when you add your field mapping (I will have a look into it when I get some free time but I'm not sure when that will be).

As far as the actual pulling in of the files goes a possible, relatively straight forward way to get your files from the external source might be to implement one of the migration methods like prepareRow() (see Commonly implemented Migration methods) and have it download the file (you could use drupal\_http\_request() or cURL or similar) for use in your file migration.

Be sure to handle the case of rollbacks and either remove the local files or before downloading, check if you already have the file then only download if you don't.

---
Tags: media, files, migrations, users
---


title: Dynamic RSS Feed in View

text:
# Question
Title: Dynamic RSS Feed in View
Passing a context from the panel to the view.

Need the view to accept the context and then consume an RSS feed.

For example: visiting /stock/MSFT would pass in MSFT to the view. The view would then hit http://finance.yahoo.com/rss/industry?s=MSFT and consume that RSS content.

I know you can consume a *static* feed with the Aggregator or Feeds module but what about a dynamic one. Any ideas?

**Thanks!!**

# Answer
> 1 votes
For those of you interested -- the only way I could figure out how to solve this was with writing a custom cTools plugin (See: What are Ctools plugin (content type, access, etc), and how does one create them?).

In that plugin I created a block and placed it in the panel.

I used Magpie RSS for the parsing/fetching of the feed.

# Answer
> 0 votes
You will need to add a contextual filter to your view (in the Advanced column).

If you have added a feed with the title MSFT, then add the contextual filter 'Aggregator feed: Title'. In the second step, configure the filter value to 'Provide default value' and type is 'Raw value from URL'. Then you can navigate to /your-page/MSFT.

---
Tags: 7, feeds
---


title: Drupal 7 single language views

text:
# Question
Title: Drupal 7 single language views
I have a website which is developed in three languages. I created a taxonomy vocabulary (product category), which is output from the views. Inside the term gallery thumbnail image products. So, how do single language for the gallery to not have to add three times the same image for multiple languages.

# Answer
you could set it to language neutral and allow both content in the selected language and language neutral to be shown
> 0 votes

---
Tags: views, taxonomy-terms, i18n-l10n
---


# Question
Title: New users not created when migrate source is nodes instead of users
I'm working on a D6-\> D7 user migration where I need the source to be a node, not a user. To get around the restriction of only one author per node, in the source D6 site we created a Source content type, and then in other node types (article, video, etc), we created field\_source as a node reference field to reference Source nodes.

So now, in my user migration to D7, I need to get the data from the Source nodes instead of users. Here's what I have so far.

```
/**
 * Override of DrupalUser6Migration.
 */
class CNSUserMigration extends DrupalUser6Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->addFieldMapping('name', 'title');
    // Set a default password for all users.
    $this->addFieldMapping('pass')->defaultValue('Pass!234');
    $this->addFieldMapping('field_twitter', 'field_twitter_id_value')->description('Twitter ID');
    $this->addFieldMapping('field_job_title', 'field_source_title_value')->description('Job title');
    $this->addFieldMapping('field_bio', 'body')->description('Bio');

    // By default, the primary key is the uid from the users table,
    // but since our user source is a source nid, need to replace
    // uid with the nid of the source node.
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'nid' => array('type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'Source node nid',
          'alias' => 'n',
        ),
      ),
      DrupalDestinationUser::getKeySchema()
    );
  }

  /**
   * Override of DrupalUser6Migration::query()
   *
   * @return mixed
   */
  protected function query() {
    // Create query from scratch to get source nodes referenced from field_source
    $query = Database::getConnection('default', $this->sourceConnection)
      ->select('node', 'n')
      ->fields('n', array('nid', 'title'));
    $query->innerJoin('content_field_source', 'cfs', 'cfs.field_source_nid = n.nid');
    $query->innerJoin('content_type_source', 'cts', 'cts.nid = cfs.field_source_nid');
    $query->fields('cts', array('field_source_title_value', 'field_twitter_id_value'));
    $query->innerJoin('node_revisions', 'nr', 'n.nid = nr.nid');
    $query->fields('nr', array('body'));
    $query->distinct();

    return $query;
  }
}

```

So my query works fine and gets all the relevant Source nodes, but when I ran it the first time, I realized I had to change my source PK to be the nid of the Source node instead of the default uid from the users table. As you can see above, I overrode the map with a new MigrateSQLMap object in my constructor. However, when I run the migration, it creates the first user from the query, but then all of the subsequent source records also point to that first new user instead of creating new users. Now that I've defined a new source PK, do I also need to do something on the destination side to cause it to create new users?

Thanks.

# Answer
It appears that my problem was that I didn't have an orderBy in my query. Once I changed it so that it looks like:

```
$query = Database::getConnection('default', $this->sourceConnection)
  ->select('node', 'n')
  ->fields('n', array('nid', 'title'));
$query->innerJoin('content_field_source', 'cfs', 'cfs.field_source_nid = n.nid');
$query->innerJoin('content_type_source', 'cts', 'cts.nid = cfs.field_source_nid');
$query->fields('cts', array('field_source_title_value', 'field_twitter_id_value'));
$query->innerJoin('node_revisions', 'nr', 'n.nid = nr.nid');
$query->fields('nr', array('body'));
$query->orderBy('nid', 'asc');
$query->distinct();

```

the problem went away.
> 0 votes

# Answer
Since you know SQL, It would be simpler and definitely quicker to use SQL and SELECT the users from the source nodes and INSERT it into the user table rather than attempting to write a PHP script.
> 0 votes

---
Tags: migrations
---


title: List of links in an article

text:
# Question
Title: List of links in an article
I want to add a field on my type of content which allows authors to select a link in a list. If author doesn't find the good link, he can directly add it and name it.

The list has to be composed with the name (title) of all links saved by all the authors of my site. All authors have to be able to add directly a new link in this list.

Any idea ?

# Answer
> 0 votes
I would create a content type for the link and then there are two options I can think of:

# Answer
> 0 votes
You can do it with Taxonomy and then Entity References with References Dialog. Actually you can do it with several different modules for the Dialog, last project I've used this one and I like it.

You create a Taxonomy term, add your fields (Link is your friend). On you Content you insert a new field as Entity Reference. If you want to print not only the name of the term (as I think you will) you might need to create a Entity Reference View (it's a views display type), to render your fields.

---
Tags: navigation
---


title: User picture and name in user menu

text:
# Question
Title: User picture and name in user menu
I would like to achieve what Acquia did on https://dev.twitter.com/. When you sign in, you can see the user picture and the user name in the right end of the menu bar and that is what I need.

I made just some basic attempts yet:

First I tried to use the Menu Token module. Tried to put user picture and user name tokens into the title. Then I realized, that you can't put html in the menu item title as it goes through check\_plain() (and it is good that way). Other problem with this was, that the menu item was shown for Anonymous users as well, and the user name was "Anonymous".

I'm using the Omega theme.

The twist on the whole problem is, that I would like to use the Superfish module as well (drop-down as on the Twitter site), and it has its own theme function for building/rendering the menu items.

I can think of a possible solution, that would be a custom theme function and a menu link alter, so that I add an image besides the title. But the Superfish module won't handle the image added to the "raw" link. Correct me if I am wrong...

# Answer
One method of doing this is to override `theme_menu_link()` in your `template.php` file. Specifically, we will be looking for the "My account" link and changing that the text to the username and adding the image.

Add the following to your `template.php` in your Omega subtheme:

```
function OMEGASUBTHEME_menu_link(array $variables) {
  global $user;
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $title = '';
  // Check if the user is logged in, that you are in the correct menu,
  // and that you have the right menu item
  if ($user->uid != 0 && $element['#theme'] == 'menu_link__user_menu' && $element['#title'] == t('My account')) {
    $element['#title'] = $user->name;
    // Add 'html' = TRUE to the link options
    $element['#localized_options']['html'] = TRUE;
    // Load the user picture file information; Unnecessary if you use theme_user_picture()
    $fid = $user->picture;
    $file = file_load($fid);
    // I found it necessary to use theme_image_style() instead of theme_user_picture()
    // because I didn't want any extra html, just the image.
    $title = theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri, 'alt' => $element['#title'], 'title' => $element['#title'])) . $element['#title'];
  } else {
    $title = $element['#title'];
  }
  $output = l($title, $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

This produces the following html for the menu item in question (my thumbnail image style is set to scale and crop 28 x 28):

```
<li class="first last expanded"><a href="/user" title=""><img typeof="foaf:Image" src="path/to/image" width="28" height="28" alt="username" title="username">username</a></li>

```

The rest is just css and possibly javascript.
> 4 votes

# Answer
I came across this issue too and just used the Menu HTML module in conjunction with Menu Tokens. This very simple module adds a checkbox to the menu item edit form and allows the admin to add html to the menu item title. This way you can use `[current-user:picture][current-user:name]` and the users picture (avatar) will show.
> 4 votes

# Answer
For D7 Bootstrap 3 users who want to use profile picture and username as a parent menu item for a "my account" menu.

I hacked the following together from the above two code samples, along with a few lines from the bootstrap menu include file menu-link.func.php.

I'm sure it's not perfect, but it's working in my install. I'm using a module (with included theme override function) instead of template.php. Note my imagestyle "avatar40" should be replaced with your own imagestyle name.

```
function MYMODULE_menu_link(array $variables) { // overrides the default "my account" link with avatar and name
  global $user;
  $element = $variables['element'];
  $sub_menu = '';
  $caret_text = '';

  if ($element['#below']) {
    unset($element['#below']['#theme_wrappers']); // remove default html menu wrappers
    $sub_menu = '<ul class="dropdown-menu">' . drupal_render($element['#below']) . '</ul>'; // add wrapper <ul> tag with bootstrap class
    $caret_text = ' <span class="caret"></span>'; // only show caret if submenu exists
  }
  $title = '';
  // Check if the user is logged in, that you are in the correct menu,
  // and that you have the right menu item
  if ($user->uid != 0 && $element['#theme'] == 'menu_link__user_menu' && $element['#title'] == t('My account')) {
    $element['#title'] = $user->name;
    // prepare bootstrap attributes for wrapper <li>, and then the <a> tag it contains
    $element['#attributes']['class'][] = 'dropdown';
    $element['#attributes']['class'][] = 'user-picture';
    $element['#localized_options']['html'] = TRUE;
    $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
    $element['#localized_options']['attributes']['data-target'] = '#';
    $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    // manually prepare picture, <a> tag with image reference, username (theme_user_picture won't work due to nested <a> tag)
    if (!empty($user->picture)) {
      $fid = $user->picture;
      $file = file_load($fid);
      $title = theme('image_style', array('style_name' => 'avatar40', 'path' => $file->uri, 'alt' => $element['#title'], 'title' => $element['#title'])) . $element['#title'] . $caret_text;
    }
    else {
      $title = $element['#title'] . $caret_text;
    }
  }
  else {
    $title = $element['#title'];
  }
  $output = l($title, $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```
> 2 votes

# Answer
Using Menu HTML + Menu Tokens breaks Menu Item Visibility. Code above works, except if user didn't set a picture. For that I do:

```
// Check if the user is logged in, that you are in the correct menu,
// and that you have the right menu item
if ($user->uid != 0 && $element['#title'] == t('User Menu')) {
  $element['#title'] = $user->name;
  // Add 'html' = TRUE to the link options
  $element['#localized_options']['html'] = TRUE;
  //isset($user->picture) always returns true, don't know why. had to use !empty
  if (!empty($user->picture)) {
     $url = file_load($user->picture)->uri;
  }
  else if (variable_get('user_picture_default', ''))
  {
     $url = variable_get('user_picture_default','');
  }
  else
  {
     $url = "public://avatars/anon.png";
  }
  $title = $element['#title'] . theme('image', array('path' => $url, 'width' => '30px', 'height' => '30px'));
} else {
  $title = $element['#title'];
}

$output = l($title, $element['#href'], $element['#localized_options']);

```
> 1 votes

---
Tags: routes, users, tokens, navigation
---


# Question
Title: Drupal always creates its own URL aliases, even when I tell it not to
I don't know if this is a bug in Drupal, or if there's a configuration somewhere that is causing the problem, but when I create a new page or edit an existing page, Drupal (always? often? sometimes?) generates its own URL alias, even though I've very clearly specified that it should NOT do this, and I've provided one. The one I provide does get created, but the Drupal-generated URL alias, which is always ugly, gets used instead. I have to manually delete the Drupal-generated alias in order for the site to work.

For instance, I just added 2 pages, "Privacy Policy" and "Terms of Use". Even though I specified `/terms` and `/privacy` as the URLs (and yes: of course I gave them to Drupal without the initial slashes), I got stuck with `/content/privacy-policy` and `/content/terms-of-use` as the URLs for these pages.

# Answer
This is an existing bug: https://www.drupal.org/node/936222. Try applying the patch there.
> 1 votes

# Answer
I've just had the same issue. I found the reason why it was behaving like that, so I thought I would post the answer here for others with the same problem.

You need to go to **Path Settings** --\> Section "**While Updating**" (I don't know the exact wording in English as I have the PT version).

Here, you have to select the first option: **Do nothing. Keep the old alternative path**.

This should solve your question. :-)
> 2 votes

---
Tags: path-aliases
---


# Question
Title: Difference between Relation and term reference field
Can anyone explain, what is the difference from practice point of view between relation (by Relation module) and term reference?

I mean if I will use as product attribute taxonomy term, what type of attribute connection I should use?

# Answer
In your case you should use https://www.drupal.org/project/entityreference

This one is lighter and does the job without overcomplicating. It simply stores 1 to n relations, which may be used later to display in Views.

Relation - this module is much more advanced and allows you to make:

1. directional references, example

* user A is "boss" of user B
2. different types of references between same entities, example:

* reference type 1: user C is "friend" of user D

    AND
    * reference type 2: user C "follows" user D
3. these references are entities itself, so they are fieldable, could be displayed in Views separately etc.
> 1 votes

---
Tags: entities
---


title: add html to fieldset

text:
# Question
Title: add html to fieldset
I try to customize fieldset ABC that are inside drupal commerce checkout page. Markup looks like this

```
<fieldset>
 <legend>ABC</legend>
 <div class="fieldset-wrapper">
  <div class="form-item"></div>
  <div class="form-item"></div>
 </div>
</fieldset>

```

I would like to put some additional code directly inside fieldset and then also some other html directly inside form-item elements. Question\> What should I do to achieve that? I found this page https://api.drupal.org/api/drupal/includes!form.inc/function/theme\_fieldset/7 would it be of any help? Thank you.

images

# Answer
Try to change it using `hook_form_FORM_ID_alter()`.

```
// Replace FORM_ID with commerce checkout form id
function hook_form_FORM_ID_alter($form, &$form_state, $form_id) {
  $form['fieldset_item']['mymarkup'] = array(
    '#type' => 'item',
    '#markup' => 'My Markup Here.',
  );
}

```
> 2 votes

---
Tags: 7, theming, commerce, forms
---


title: form submit function never gets called.

text:
# Question
Title: form submit function never gets called.
My drupal form submit function is not called. validation function is called. Form name is `Mymodule_user_profile_form($form, &$form_state)`, validation function name is `Mymodule_user_profile_form_validate($form, &$form_state)` and submit function name is `Mymodule_user_profile_form_submit($form, &$form_state)`. I have studied all the previously asked questions.

This is the last portion where I declare my submit button is defined.

```
$form['profile']['profile-share']['profile-save-reset-btn']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Spara'),
  //'#name' => 'save-profile',
);

```

I have tried like this.

```
$form['#submit'][] =  'Mymodule_user_profile_form_submit';

```

var\_dump($form\['#submit'\]); Shows the submit function but it's never called. Any Idea about this?

# Answer
> 0 votes
The submit function is correct. By default, Drupal should call `Mymodule_user_profile_form_submit()` function without declared it with the '#submit' attribute. Could you publish all the code to have a deeper exploration of it?

---

Edit:

You could try this:

```
$form['profile']['profile-share']['profile-save-reset-btn']['submit']['#submit'][] =  'Mymodule_user_profile_form_submit';

```

The atrribute is in the upper side of the rendering array. The attibute should be at the same level to be fired when the submit button is pressed:

Here an example of form api reference:

```
$form['actions']['delete'] = array(

  '#type' => 'submit',

  '#value' => t('Delete'),

  '#weight' => 15,

  '#submit' => array('node_form_delete_submit'),

 );

```

You could also attach the '#submit' in the upper level if you declare '#type' as 'form'. For example:

```
$form['#type'] = 'form';
$form['#submit'] = array('your_function');
$form['first_tree']['element'] = array( ... ) ;
$form['second_tree']['element'] = array( ... ) ;

```

# Answer
> 0 votes
If your explanation is true, this should be working as you have described.

Submit functions only run if the validate function doesn't throw any errors. What are you doing in your validation function? Try just leaving it empty and returning `TRUE` to see if submit runs.

If you have the `devel` module enabled, put a `dpm('Submit function ran');` in the submit function and likewise in the validate function.

# Answer
> 0 votes
This code has been taken from the form api reference:

```
 $form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#weight' => 15,
  '#submit' => array('Mymodule_user_profile_form_submite'),
 );

```

The above code may help you to define your submit button and it's callback function when the form is submitted. Hope this helps you.

# Answer
> 0 votes
In your template file, try printing the form id,form token and form build ID

```
print render($form['form_token']);
print render($form['form_id']);
print render($form['form_build_id']);

```

Even if the these values are not present,the form callbacks will not work

---
Tags: forms, users
---


title: filter based on user reference

text:
# Question
Title: filter based on user reference
I have a content type "book" that has an entity reference field that references users and pulls in a name. Users also has fields for a picture and an author website.

I would like to add a block at the bottom of each book node that shows the author picture and website.

What is the correct way to set up the relatioknship and filter when there is no user ID in the URL?

# Answer
> 0 votes
1. **Set up the relationship**. Under the **Relationships** section click + to add a relationship.

* Under "Add relationships" you will see all fields listed.
    * Drop down the Groups menu and select "Content".
    * Locate your node reference field, for example '**Content: Reference user (field\_reference\_user)**'. Check the box to the left of it.
    * Click the Add button.
    * Check the box labeled 'Require this relationship', and click the Update button.
2. **Add a Contextual filter** for Node ID. Set the default value -\> get ID from URL
3. **Add a field.** Click + next to Fields. Under Groups, select Node, and choose Node: Title. Under Relationship, select your node reference field, e.g., Reference user, click Update.

Create a view on a node reference field will explain you in detail

---
Tags: views, users, entities
---


# Question
Title: Print title of block group to allow for collapsible group
Currently I am working on a site where I need groups of blocks which should be collapsible. The blocks are grouped by using block group module. For the collapsible part I am using collapsiblock. By default the block group is rendered in a simple div, which I change by applying a template to add the title. But the title is not available as a variable, because block group module uses the title field only for administration and thus the $title variables are all empty.

Does anybody know how to access the variable in a template file?

# Answer
> 0 votes
I'm about to do something similar, but I imagine you could do a preprocess and populate the variable yourself.

-- EDIT --

As a matter of fact, I am sure of it. Just did it myself.

In template.php write a hook\_preprocess\_region() function.

```
function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'blockgroup_regionname') {
    $variables['title'] = 'Title';
  }
}

```

Then just in your template.

```
<?php if ($title): ?>
  <h2 class="title"><?php print $title; ?></h2>
<?php endif; ?>

```

Which in turn should make the variable available to whatever else you are trying to do. SHOULD anyway. Good luck!

---
Tags: blocks
---


title: Add node ID to template variables

text:
# Question
Title: Add node ID to template variables
is there any way to add node ID (if it exists) to template variables using

```
my_theme_preprocess_page(&vars) function?

```

It looks like theme theme isn't using `my_theme_preprocess_node(&$vars, $hook)` so I assume that node object isnt available in vars for `my_theme_preprocess_page(&vars)`.

It's not my website so I don't really know the structure.

# Answer
> 2 votes
If you want to access `nid` inside preprocess\_page you should try something like this

`arg(0)` will return `'node'` and `arg(1)` will return `node nid`.

Provided you must be inside a node.

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
   $node = node_load($nid);
   // creating the node variable
   $vars['node'] = node_load(arg(1), NULL, TRUE);
  }
}

```

---
Tags: theming
---


# Question
Title: Organic Groups - How do I set a default role for new group members?
I have created a custom group role with some custom permissions and I am trying to find a way to allocate this role to group members by default. Ideally I would like every member of every group to be allocated this role, and be able to remove this role from a user if I no longer want the particular user to have my custom permissions.

I believe OG User Roles had this functionality and user roles were put into core organic groups for 7 but I am not sure if this default roles functionality was also implemented?

# Answer
I found a solution to this by using og\_role\_grant within hook\_og\_membership\_insert and hard coding my role in there. This works by granting the role to a user who has just been added as a member of a group. If I had more time I would create myself a form in the backend so it wouldn't be hard coded but for now this seems to work fine.

```
function MODULENAME_og_membership_insert(OgMembership $og_membership) {

  if('user' == $og_membership->entity_type && is_numeric($og_membership->etid)){
    $roles = og_roles($og_membership->gid);
    foreach($roles as $key => $value){
      if ('ROLE_NAME' == $value) {
        og_role_grant($og_membership->gid, $og_membership->etid, $key);
      }
    }
  }
}

```
> 0 votes

# Answer
Yep, this is not provided by default, i'd spen hour understanding that by default users have no role in group where they was added. Maybe i cant find that setting... But seems like for now using hook\_og\_membership\_insert is only solution
> 0 votes

---
Tags: 7, organic-groups
---


title: Master Detail page for taxonomy terms

text:
# Question
Title: Master Detail page for taxonomy terms
I'm essentially trying to recreate the results of this question, but using taxonomy terms instead of nodes.

I have my master view (a list of taxonomy terms from a vocab') `item-view`, which has the term ID (TID) and I've re-written it to link to the other view `item-details/[tid]`.

On the detail view I have a contextual filter of Taxonomy term: Term ID (to match the field in the other view) and my `Argument Input` settings match those in the previous answer (namely: 'From Panel Argument' for the list box 'Taxonomy term: Term ID source', then 'First' from Panel argument.)

But on the page (`item-page`) that holds both views in separate columns, it just links through to the detail view, at `item-details/[tid]`, opening the url in the browser rather than enacting that special drupal magic that makes it appear in the right hand column.

Does this not work with Terms and TIDs? Or have I missed something?

# Answer
> 2 votes
> The Master page is at item-view and the links of there point to item-details/\[tid\], the detail view is at item-details/\[tid\] for each item.

In reality the links on the master page shouldn't link *to* the details view, but just to the current page with `/[tid]` appended.

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


title: Error in Pager of a Ajax View

text:
# Question
Title: Error in Pager of a Ajax View
I am getting the following error in Ajax Enabled View, which uses Load More Pager.

I am not sure if its, entirely because of OG, as the error doesn't appear in Views Preview but only in the actual view rendering in a page.

# Answer
I was able to figure out the issue. Its a bug in the views which doesn't handle the nested views. More about this issue can be found in https://www.drupal.org/node/1016602

I had to override a javascript function in views to fix it. But since it was very use-case specific, I am not sharing the details of the same.
> 0 votes

---
Tags: 7, views, ajax, organic-groups, paging
---


# Question
Title: How can I display the list price field in product page?
I am new to commerce Kickstart. I can add the list price field in hats content types. But i can't to show the list price field in product page. I don't want to show the SKU field in product page.In node--product-type.tpl.php

.. But it doesn't work it..

# Answer
it much be easier to add a '*product reference*' to your product type when you define the '*content type*'. and simply the '*Product: Price*' field will add to your '*manage display*' in that '*content type*' if the price doesn't show up, Modify the settings for the price field on the product type "manage display" configuration.
> 1 votes

---
Tags: nodes, commerce
---


# Question
Title: How does drupalxray.com find out the modules present on a thirdparty website?
drupalxray.com gives an exhaustive list of the modules present in a third party website. How does it ascertain which are the modules present on a site?

Note : It also identifies the modules which are not enabled.

Based on How to determine the modules enabled on a third party website? but making it a separate question as others might find it useful.

# Answer
> 10 votes
I enabled access log on my site and then let www.drupalxray.com to review my site.

The entries in the access log looked like below.

```
HEAD /sites/all/modules/token_custom/LICENSE.txt HTTP/1.1
HEAD /sites/all/modules/active_tags/active_tags.js HTTP/1.1

```

As you can infer, looks like they have an exhaustive list of static files in all the modules that they can ascertain through their service.

1. They are using HEAD requests to save the bandwidth.
2. If the HEAD requests return 404 response code, the module is not present in the code base if it gets a 200 response code then it can ascertain that the module is present.

However it would be good to know if they have a list of modules with static files or if they have automated that to find the static files all the module on drupal.org.

The suggestion to enable access log was made by Clive.

Note : Currently the services only looks at the `sites/all/modules` folder only. But I think they can easily tweak a little to make it more generic.

---
Tags: 7
---


# Question
Title: How do I setup multi sites in Drupal 7 using xampp
I face a problem in multisite with Drupal 7.34. I'm using windows 7 Os. The steps that I followed are:

**1. Create a database for all sites :** create db of all sites test\_db, trial1\_db and trial2\_db.

**2. Install Drupal :** I installed the drupal 7.34 as usual and name it test.

**3. Tell Windows and Apache about the multiple sites :** Open Windows 'hosts' file in a text editor. Which is typically in /system32/drivers/etc/hosts. And add following lines:

```
                   127.0.0.1 test
                   127.0.0.1 trial1
                   127.0.0.1 trial2

```

Now in httpd-vhosts.conf file, which is located in c:/xampp/apache/conf/extra. I append these lines at end of the file:

```
                   NameVirtualHost *:80
                   <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs"
                     ServerName localhost
                   </VirtualHost>

                   <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs/test"
                     ServerName test
                   </VirtualHost>

                  <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs/test"
                     ServerName trial2
                  </VirtualHost>

                  <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs/test"
                     ServerName trial3
                  </VirtualHost>

```

and make sured that these are not commented in httpd.conf.

```
                LoadModule rewrite_module modules/mod_rewrite.so
                Include conf/extra/httpd-vhosts.conf

```

**4. Create directories for the sub-sites:** Navigate to c:/xampp/htdocs/test/sites and create the directories 'trial1' and 'trial2'. And copy the default-settings.php file to each directory and rename it to settings.php. And also set the permission of these file. I mean these files are not readonly.

**5. Install the sub-sites :** In an open browser, navigate to `http://trial1` or `http://trial1/install.php`

But here I got "Object Not Found!".

I followed the these links also.

https://www.drupal.org/node/288126

https://www.drupal.org/node/1682040

http://www.dratek.com/node/77

How do I setup multiple sites with one database in Drupal 7

# Answer
Thanks @Sumit Madan for your suggestion. My issue has been resolved now. I just append these lines in test/sites/default/settings.php:

```
  $sites['trial1.com'] = 'trial1.com';
  $sites['trial1.localhost'] = 'trial1.com';

  $sites['trial2.com'] = 'trial2.com';
  $sites['trial2.localhost'] = 'trial2.com';

```
> 1 votes

---
Tags: multi-sites
---


# Question
Title: Problem using tokens when mailing to site owner after an order
I'm new to drupal

**What I want to do:**

After a user places an order I want to send an email to the site owner with information of the order. These 2 tokens (that are standard) are working:

```
[current-user:name]
[message:message-commerce-order:order-number]

```

I navigate to structure \> messages \> (here I made a new message) commerce order: order confirmation to admin \> edit

path = `admin/structure/messages/manage/commerce_order_order_confirmation_to_admin`

@ the end of this page I can select tokens

**My problem:**

When I select a token at the bottom of the edit page and I paste it in my email body, and I actually receive the email, the variable of the token isn't shown. It only gives me the token itself.

For example the token for price doesn't work

```
[message:message-commerce-line-item:commerce-product:commerce_price]

```

What am I doing wrong, am I missing some steps?

Do I need to add a rule to the fields of the checkout order steps? But when I choose for shipment it's with radio buttons, so not exactly a field.

# Answer
This is an answer on my case:

The problem was that the selected data was wrong. It was commerce-order and it had to be entity-created:message-commerce-order.

Go to: configuration \> Workflow (Rules) \> {select your rule} in my case it's Commerce order message: order notification mail to admin \> set a data value

In set a data value change the selected data to entity-created:message-commerce-order
> 0 votes

# Answer
I encountered similar issues in the Rules email body. Standard input filters were being applied to the field. You may need to install the Token Filter module and configure input formats accordingly.
> 0 votes

# Answer
You can create you own custom tokens with hook\_token\_info(). See more info at https://www.drupal.org/node/1308488. That might be a workaround for you.
> 0 votes

# Answer
I have the following suggestions for you.

1. Check if your price field is a multi-valued field. If yes, then the token will mostly be of the form \[message:message-commerce-line-item:commerce-product:commerce\_price:0\] (for first item),\[message:message-commerce-line-item:commerce-product:commerce\_price:1\] (for second value) and so on.
2. Replace \[message:message-commerce-line-item:commerce-product:**commerce\_price**\] with \[message:message-commerce-line-item:commerce-product:**commerce-price**\] (Yes,even a hyphen can make a difference!)
3. Click on 'Switch to Data selection' button below your email body, a dropdown will appear. Go on filtering your field till you find the **commerce\_price** field. Then, copy it, click on 'Switch to direct input mode' and paste it in your email body.

Hope this helps.
> 0 votes

---
Tags: emails, commerce
---


title: Delete a node and a menu_link

text:
# Question
Title: Delete a node and a menu_link
I have a simply question, it's possible to delete a node and at the same time delete a menu\_links ? For exemple when i will use the button delete of a node of my entity "PROJECT" i want to delete automaticaly a menu\_links created before. I found the HOOK\_Delete but how to use this function in a particular entity ? Like the HOOK\_form\_alter we can choose the form\_id, there is a HOOK like this ? :

```
Mymodule_delete($nid) {
    if($entity == "project") {
        delete($nid);
    }
}

```

Maybe can i change the `$form['actions']['delete ??']` in my form alter and use my own function ?

```
_myfunction_delete_project($nid) {
    $query = "Here get the entity of my $nid";

    if($query == "project") {
        delete($nid);
        delete($my menu links);
    }
}

```

I hope you understand my request

Thanks

# Answer
> 0 votes
You can do it simply using hook\_node\_delete.

```
function hook_node_delete($node) {
  if ($node->type == 'any_content_type') { // for specific content type
    // here your code use $node->nid
  }
}

```

---
Tags: nodes, routes
---


title: Add a module as cron job

text:
# Question
Title: Add a module as cron job
I have a module file which fetch data from a link. I have to run this module as a cron everyday. How can I do it?

# Answer
You have to implement hook\_cron to run you task periodically on drupal cron.

```
function hook_cron() {
  // Your code here
}

```
> 0 votes

---
Tags: cron
---


# Question
Title: Field Permission Issue even without Field Permission Module
I ran into a strange issue.

I have a content type with a field for user-reference (say XYZ). Now, I used the module nodeaccess\_userreference to grant the referenced users in the field XYZ the permission to edit the node.

The edit button did show up and the referenced user was able to edit the content except for one field : "Body" field!!

I've no module for field permissions or anything like that. Why is it happening? All the fields are editable. I've been trying to debug the issue but so far no clue.

Kindly suggest what the problem might be or some approach to debug it.

I will update here as soon as I find some solution.

**UPDATE**: The issue has been resolved. It was a text-format permissions issue. If anyone ever comes across such an issue, be sure to check your text-format permissions. They are the ones that never cross your mind.

# Answer
> 0 votes
Sorry to trouble you guys, but I figured it out just now. It was really a silly mistake from my side, but I had been hitting my head ever since.

Anyways, turned out that I had not provided the permission to the user for that particular text format!! The article was created by admin using "Full HTML" but the user had no permission for that format.

Anyways, I figured it out using a **hack method which was really cool**.

The text box was showing this message when it denied permission :

```
This field has been disabled because you do not have sufficient permissions to edit it.

```

I copied this and searched for this complete sentence in the contributed as well as core modules' directory. The "culprit" was filter.module. The function which was doing this was properly commented and said that "deny the users with no permission to the given text format".

---
Tags: users
---


title: Grouping Nodes by first letter of field

text:
# Question
Title: Grouping Nodes by first letter of field
I've around 300 pages in wiki style (word -\> explanation).

I need to create an overview page with all words categorized by first letter of page title/custom field (so basically \[0-9\] or a, b, c etc).

I would like to know you there are any already some good solution to do that? Also considering in best way to go :)

I need something like this (actually in 3 columns)

Thanks.

# Answer
> 0 votes
I ended up with solution from @Colin Shipton + `column-count` CSS property. That solutions works in all browsers except IE9 and less.

# Answer
> 10 votes
Add the field a second time so it appears twice in Fields, check exclude from display and uncheck link this field to the original piece of content. Under rewrite results check trim this field to a maximum length, and enter 1 in the textfield.

Under format click settings next to unformatted list, etc. and select the right field in the grouping options.

You'll probably need to adjust the sort criteria too

# Answer
> 1 votes
Please Refer this, it may help you out.
https://www.drupal.org/node/1078962.

# Answer
> 0 votes
* Create a *view* of that content type
* Remove *published date sort criteria* and add the field you need as sort criteria in *ascending order* . It appears as `Content: Title (asc)` in sort criteria

# Answer
> 0 votes
Sir,

Click "theme information" then look at the name of the file that applies to the node reference field.

Create a .tpl.php file with a candidate name that's specific enough for your needs will be something like views-view--viewname--fieldname.tpl.php.

Click the link for the template file in use in theme information for this field, and views will show you the code in that file. Copy & paste that code to your new file.

In the new file, you'll want to write a little PHP to output your links as a list. If you enable the devel module, put in the page, and inspect what's available. One of them will be an array of links. Output that.

Thank You.

---
Tags: views
---


# Question
Title: Show block on all 404 / 403 pages only via context
Without having to install even more modules on the site for context. I know there a boat load of plugins for context, but I was wondering if this can be achieved by just using core context:

I basically want to show a view block on all the 404/403 pages, which are just basic page nodes. The problem with context is when you choose path as the condition, it will only show up on that path, which is the 404/403 node paths only. Even if you put in something random like: foo.com/adsfadsf -- the context won't fire since its not a recognized path even though it is the 404 page.

What context recipe can restrict a block to show up on the error pages only? I know i can list out all the paths i dont want it to show up on, but thats not going to work in my scenario.

# Answer
> 1 votes
A better way to do this is create a panel page for 403 and 404 page. Add whatever you want to in the panes.

Set the 403 and 404 page path under :

```
Admin > Configuration > System > Site Information

```

There is a section called `ERROR PAGES`. Add both the path there.

**Edit :**

For context use Context Error module.

---
Tags: blocks, 7
---


# Question
Title: Odd log entries: is it indicative of an attack?, is there anything other than IP blocking that I should do?
So I've been getting some odd log entries in my Drupal 7 install: Here's two:

As far as I can see they haven't done anything and I've blocked the IP addresses but they keep coming with different IP addresses so I'm wonder what they actually mean? Like if they were for `manager/html` I'd know they were (probably automated) attack testing for Apache Tomcat apps to hack. But these with a location that isn't even my site I'm confused by. Also wondering why the message starts with `ttp://` instead of `http://` or something normal.

# Answer
> 1 votes
Well continued my research and a day without no answer was enough time for me to figure it out. As I suspected yes this is an attempted attack/test. It is not specifically an attack on Drupal although it does show up in the Drupal log.

Specifically this is checking to see if your server is set up in such a way that it can be used as an open proxy; in other words if you give it a get request for a domain it doesn't serve will it GET the content from the right server and pass it on. This is bad without a login, since it lets *anyone* appear to be your server while they are spamming/etc - see the Apache Proxy Abuse Page.

In this case since Apache passed the request on to the virtual hosts it shows that the server is **not** configured as an open proxy and is safe (at least from that attack vector at this time). The server logs show a 404 as well which confirms that either the url was invalid or that there is no open proxy:

```
125.64.35.67 - - [03/Dec/2014:08:08:52 -0500] "GET http://6.url.cn/zc/chs/img/body.png HTTP/1.1" 404 716 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.3072; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0)"

```

If it was a successful attack test/attack it wouldn't appear in the Drupal logs, only in the server logs. In the server logs it would appear something like:

```
125.64.35.67 - - [03/Dec/2014:08:08:52 -0500] "GET http://6.url.cn/zc/chs/img/body.png HTTP/1.1" 200 716 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.3072; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0)"

```

with a response code that indicates a valid resource.

As to why the Drupal log strips the initial `h` for the message I don't know and it doesn't really matter; that being said if I have time I'll probably investigate it and submit a patch to fix it.

---
Tags: security
---


# Question
Title: How do you swap position of Order Total Components in Checkout Pane?
In Commerce Shopping cart contents checkout pane, how do you swap the position of order components? We want the Sales Tax to appear -below- the Shipping.

# Answer
Do it in a custom module implementing hook\_commerce\_price\_formatted\_components\_alter(). See commerce\_price.api.php for parameter information.
> 1 votes

# Answer
I dunno if this is kosher, but I'm answering my own question because, although Ryan's answer is 'correct', I figured others who are as baffled as me might appreciate a bit more detail. The trick is to alter the weight of each component.

Also, if this can be optimised, I'm all ears. Maybe there's an 'array\_swap' function in PHP of which I'm unaware?

Finally, it would be nice if each component could somehow be labelled into categories ('tax', 'discount', 'subtotal') in case there are multiple components to be swapped so I could address the elements semantically. Eg. some tax jurisdictions in America have -4- sales taxes.

```
function jch_utilities_commerce_price_formatted_components_alter(&$components, $price, $entity)
{
    // if there is a tax component there will be more than 3 components and it seems to appear as the 3rd element.

    // swapping the weight member of each element automatically causes the display to resort.
    $s = sizeof($components);
    if ( $s > 3 ) {
        $x = 0;
        $w2 = 0;
        $w3 = 0;
        foreach($components as $c) {
            if($x == 1)
                $w2 = $c['weight'];
            if($x == 2)
                $w3 = $c['weight'];
        $x++;
        }
        $x = 0;
        foreach($components as $c) {
            if($x == 1)
                $c['weight'] = $w3;
            if($x == 2)
                $c['weight'] = $w2;

        $x++;
        }
    }
}

```
> 0 votes

---
Tags: theming, commerce
---