title: javascript code wrapper

text:
# Question
Title: javascript code wrapper
While using drupal 7, is it necessary for to wrap pure javascript code with jquery wrapper? (I understand that while working with jquery, I need to wrap my code inside beaviors.)

code

```
function openWin()
  {
    mycode
  }

```

od should I wrap it like this

```
(function () {

function openWin()
  {
mycode
  }

  })();

```

Or even use behaviors? Thank you.

# Answer
> 1 votes
You don't *have* to wrap your code with a behavior or jQuery at all. That depends:

**If you want to use jQuery object with the `$` as a shorthand:**

Wrap your code like this:

```
(function($){
  //$('#something').show();
})(jQuery);

```

**If you want to execute something after an Ajax DOM change and on document ready event**

*Use behaviors.*

```
Drupal.behaviors.ysu_premium = {
  attach: function (context) {
    //jQuery('#something').show();
}}

```

*You can wrap the behavior with the above jQuery wrapper if you want to use jQuery.*

```
(function($){
  Drupal.behaviors.something_unique = {
    attach: function (context) {
      //$('#something').show();
    }}
})(jQuery);

```

When I'm working on Javascript, I always use the last snippet above.

---
Tags: 7, javascript
---


title: Page works with SSL, but not internally

text:
# Question
Title: Page works with SSL, but not internally
I struggled a long time with Drupal in order to get my page to load with SSL. I ended up getting it to work my modifying `settings.php`:

```
/**
 * Base URL (optional).
 *
 * If Drupal is generating incorrect URLs on your site, which could
 * be in HTML headers (links to CSS and JS files) or visible links on pages
 * (such as in menus), uncomment the Base URL statement below (remove the
 * leading hash sign) and fill in the absolute URL to your Drupal installation.
 *
 * You might also want to force users to use a given domain.
 * See the .htaccess file for more information.
 *
 * Examples:
 *   $base_url = 'http://www.example.com';
 *   $base_url = 'http://www.example.com:8888';
 *   $base_url = 'http://www.example.com/drupal';
 *   $base_url = 'https://www.example.com:8888/drupal';
 *
 * It is not allowed to have a trailing slash; Drupal will add it
 * for you.
 */
 $base_url = 'https://www. ... .com';  // NO trailing slash!

```

But now I am faced with an entirely new issue, one related to the changes I made in `setting.php`.

Now, when I try to reach my page internally by `192.168.1.x/?q=user`, I get a terribly messed up login page, and after entering my login information, I get redirected to a page that shows nothing but "SSL connection error".

What have I done!? Will this ever work?

# Answer
> 1 votes
So, I have to give props to @Darvanen for pointing me in the right direction, but my answer was a little more complex.

Because you can never guarantee what will be a part of the `$_SERVER` array, I have done a check against many different indexes of the array:

```
    if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
|| (!empty($_SERVER['HTTP_CF_VISITOR']) && strpos($_SERVER['HTTP_CF_VISITOR'], 'https') !== false)
|| $_SERVER['SERVER_PORT'] == 443)
{
    if(!empty($_SERVER['HTTP_HOST']))
    {
        $base_url = 'https://'.$_SERVER['HTTP_HOST'];
    }
    else
    {
        $base_url = 'https://www.example.com';
    }

    error_log("base_url set: ".$base_url, 0);
    error_log(print_r($_SERVER, true), 0);
}
else
{
    if(!empty($_SERVER['HTTP_HOST']))
    {
        $base_url = 'http://'.$_SERVER['HTTP_HOST'];
    }
    else
    {
        $base_url = 'http://www.example.com';
    }
    error_log("base_url set: ".$base_url, 0);
    error_log(print_r($_SERVER, true), 0);
}

```

I've tested this logic over and over again, and, so far, it appears to work in every case.

If you are wondering why I used:

```
$base_url = 'https://'.$_SERVER['HTTP_HOST'];

```

and

```
$base_url = 'http://'.$_SERVER['HTTP_HOST'];

```

it is because I have multiple domain-names redirecting to the "same-page".

Doing this allows the user to keep the same domain name that they entered the site with.

# Answer
> 2 votes
Try this:

```
$base_protocol = empty($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ? 'http' : 'https';
$base_url = $base_protocol . '://www.mysite.com';

```

Though you may need the Secure Pages module for it to work, or to have redirection set up in your .htaccess file or virtualhost.

---
Tags: 7, ssl
---


# Question
Title: Render multiple values of a field in Drupal 7
I created a custom content type with a field with multiple values which I want to render as follows in my `node--custom_content.tpl.php`;

```
<div class="CLASS" style="background: url('<?php print file_create_url($node->field_creation_images['und'][0]['uri']);; ?>')"></div>

```

However, this renders only the first value of the field. Is there a foreach solution to my problem?

# Answer
For multivalue field it makes the field value array like :

```
// $node->field_creation_images['und'][0]['uri'];
// $node->field_creation_images['und'][1]['uri'];

```

So to print all values you need to use foreach :

```
<?php foreach ($node->field_creation_images['und'] as $uri) { ?>
  <div class="CLASS" style="background: url('<?php print file_create_url($uri['uri']); ?>')"></div>
<?php } ?>

```
> 1 votes

---
Tags: entities, theming
---


# Question
Title: Security concerns with cache_get() and cache_set()
are there any security concerns with Drupal's cache\_set() and cache\_get() functions? I mean, I receive some values through an Ajax-GET-request. Can I pass them to the two functions with the following validation?

Javascript:

```
//token was passed through drupal_add_js() to Drupal.settings.my_module
var url = path + token + '/' + var1 + '/' + var2;
$.get(url);

```

Page callback:

```
function my_module_ajax_callback($token, $var1, $var2) {
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
      && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
      && is_numeric($var1)
      && drupal_valid_token($token, $var1)) {

    if (is_numeric($var2) && $var2 >= 0 && $var2 < 3600) {
      //can I pass $var1 and $var2 to cache_get() and cache_set() at this point? e.g.:
      cache_set(var1, var2);
      //Are there still security risks?
    }
  }
}

```

I would welcome every advise.

Thanks!

Daniel

# Answer
> 1 votes
currently there are no known bugs which would cause any security issue using cache\_set and cache\_get. You can put any values there both key and value are escaped. for example you can try this key `'; drop table abr;--'` and it will be saved without any issues

---
Tags: 7, ajax, caching, security
---


# Question
Title: title_callback not working for certain user in hook_menu
I am developing a module to manage Human Ressources. I implement hook\_menu with a title\_callback like this:

```
$items['intranet/hr/%user'] = array(
  'title callback' => 'user_page_title',
  'title arguments' => array(2),
  'page callback' => '_hr_redirect_to_personal_data',
  'page arguments' => array(2),
  'access callback' => 'hr_check_menu_access',
  'access arguments' => array(2),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'navigation',
);

```

Users with certain role and the user to whom the HR data belongs can access to this menu, and should see the name of the concerned user. It works perfectly if the logged user has a role, but the title of the menu is "Home" for the user to whom the HR data belongs. I don't understand what's happening as I am implementing hook\_menu() the same way the user module does for the user profile page. If I inspect the menu with the devel menu, the title is correct for every user. Any idea on what I am doing wrong ? Thanks!

# Answer
> 0 votes
I get it !

In my configuration, the path intranet/hr is a view which is not accessible to every user, that's why the children element is not accessible and I have "Home" as the menu title.

Even if I don't know how to change this behaviour, at least I know why it is happening :-)

---
Tags: users, routes
---


title: Changing textfield into textarea

text:
# Question
Title: Changing textfield into textarea
I hope I'm right here with my request and someone can help. I'm working on a website with Drupal, but am not a trained programmer.

I use a module which allows me to display a tooltip in Drupal. By default, this is defined as type "textfield" and therefore has a maximum of 128 characters. As I need more characters, I have changed the "textfield" into "textarea". As a result, I have more characters available. If I save the tooltip it is recognized and displayed correctly in the frontend. Only when I edit the tooltip again, the entered text is gone.

Here's the code (the change I made is on line 25):

```
<?php

/**
 * @file
 * module for adding a link to a block title tooltip.
 */

/**
 * Implements hook_form_alter().
 */
function block_title_tooltip_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'block_admin_configure' || $form_id == 'block_add_block_form') {
    $block = new stdClass();
    $block->module = $form['module']['#value'];
    $block->delta = $form['delta']['#value'];
    $title_tooltip_data = block_title_tooltip_get_data($block);
    $form['settings']['block_title_tooltip'] = array(
      '#type' => 'fieldset',
      '#title' => t('Block Title Tooltip Settings'),
      '#collapsible' => TRUE,
      '#weight' => 0,
      '#tree' => TRUE,
    );
    $form['settings']['block_title_tooltip']['title_tooltip'] = array(
      '#type' => 'textarea',
      '#title' => t('Title Tooltip'),
      '#default_value' => $title_tooltip_data,
      '#description' => t('Block Title tooltip.'),
    );
    if (!isset($form['block_settings']['#weight'])) {
      $form['block_settings']['#weight'] = -1;
    }
    $form['#submit'][] = 'block_title_tooltip_form_submit';
  }
}

/**
 * Implements hook_block_view_alter().
 */
function block_title_tooltip_block_view_alter(&$data, $block) {
  if (isset($data['content']) && is_array($data['content'])) {
    $data['content']['#attached']['css'][] = drupal_get_path('module', 'block_title_tooltip') . '/css/block_title_tooltip.css';
  }
}

/**
 * Implements hook_form_submit().
 */
function block_title_tooltip_form_submit($form, &$form_state) {
  $block = new stdClass();
  $block->module = $form['module']['#value'];
  $block->delta = $form_state['values']['delta'];
  $title_tooltip = $form_state['values']['block_title_tooltip']['title_tooltip'];
  $data = array(
    'title_tooltip' => $title_tooltip,
  );
  if (empty($title_tooltip)) {
    block_title_tooltip_delete_data($block);
  }
  else {
    block_title_tooltip_save_data($block, $data);
  }
}

/**
 * Function to delete block data.
 *
 * @param object $block
 *   The block object.
 */
function block_title_tooltip_delete_data($block) {
  if (!isset($block->module) && !isset($block->delta)) {
    return FALSE;
  }
  $result = db_delete('block_title_tooltip')
  ->condition('module', $block->module, '=')
  ->condition('delta', $block->delta, '=')
  ->execute();
}

/**
 * Function to save Block title tooltip data.
 *
 * @param object $block
 *   The block object.
 *
 * @param array $data
 *   Array containing data.
 */
function block_title_tooltip_save_data($block, $data) {
  if (empty($block->module) || empty($block->delta)) {
    return FALSE;
  }

  // Remove old settings.
  $result = db_delete('block_title_tooltip')
  ->condition('module', $block->module)
  ->condition('delta', $block->delta)
  ->execute();

  // Save new settings.
  $result = db_insert('block_title_tooltip')
  ->fields(array(
      'module' => $block->module,
      'delta' => $block->delta,
      'tooltip' => $data,
      ))
    ->execute();
  drupal_set_message(t('Your configuration save.'));
}

/**
 * Implements hook_preprocess_block().
 */
function block_title_tooltip_preprocess_block(&$vars, $hook) {
  global $user;
  if ($hook == 'block') {
    $data = block_title_tooltip_get_data($vars['block']);
    if ($data) {
      $vars['block']->title_tooltip = (isset($data['tooltip'])) ? $data['tooltip'] : NULL;
      $vars['block']->title_tooltip = $vars['block']->title_tooltip;
      $display = (isset($data['display'])) ? $data['display'] : TRUE;
      if (!empty($vars['block']->title_tooltip) && $display) {
        $arbitrary_array = array(
          'path' => drupal_get_path('module', 'block_title_tooltip') . '/image/callout.gif',
          'attributes' => array('class' => 'block_title_tooltip'),
        );
        $vars['block']->subject = '<div class="tooltip">' . $vars['block']->subject . '<span>' . theme('image', $arbitrary_array) . check_plain($vars['block']->title_tooltip) . '</span></div>';
      }
    }
  }
}

/**
 * Function to return the data associated with a block_title_tooltip.
 *
 * @param object $block
 *   object of Block
 *
 * @return array
 *   A renderable array containing display_link and title_tooltip variable.
 */
function block_title_tooltip_get_data($block) {
  if (!isset($block->module) && !isset($block->delta)) {
    return FALSE;
  }
  $result = db_select('block_title_tooltip', 'btt')
  ->condition('btt.module', $block->module, '=')
  ->condition('btt.delta', $block->delta, '=')
  ->fields('btt', array('tooltip'))
  ->execute()
  ->fetchAssoc();
  if (is_array($result)) {
    return $result;
  }
  else {
    return FALSE;
  }
}

```

Can anyone tell me what I have to change so that the tooltip is stored properly. I suspect that under the heading "\* Function to save tooltip title block data." something needs to be adjusted.

I also get this warning (maybe it has to do with it):

> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain() (Zeile 1573 von C:\xampp\htdocs\drupal722\includes\bootstrap.inc).

Perhaps somebody sees the mistake?

# Answer
> 0 votes
This code is little bit crazy.

it saves tooltip to db, but in frontend it doesnt use it: `function block_title_tooltip_preprocess_block(&$vars, $hook) {
 .......
 $vars['block']->title_tooltip = (isset($data['tooltip'])) ? $data['tooltip'] : NULL;
 $vars['block']->title_tooltip = $vars['block']->title_tooltip;` in first line there is code from db, but it takes another value - from block settings.

so there are 2 ways to fix it:

1. probably in your tooltip db field there is set max length. So you need to changed to text. You need to update schema in .install file and write update function to update it.. or you can just change it directly in db. if you don't know how to fix .install file.
2. another option. I'm not sure it is going to work. write this: `function block_title_tooltip_form_alter(&$form, &$form_state, $form_id) {
 echo""; print_r($form_state); die();`

this code will print all values of $form\_state. I assume that somewhere inside $form\_state there should be value of your tooltip. because it is available in frontend function. So search for it. And then if you find it use it instead of this: `//change this line
 '#default_value' => $title_tooltip_data,
 //to someting like this:
 '#default_value' => $form_state['title_tooltip']`

---
Tags: tooltips
---


title: Allow .oft file extension

text:
# Question
Title: Allow .oft file extension
How to allow media module to support `.oft` file extension?

Checked supported file extensions in `includes/file.mimetypes.inc`. It does not have `oft` extension listed. How can I add it without hacking core files?

# Answer
To add mime types without hacking core files, you will want to create a new module and use the hook\_file\_mimetype\_mappings\_alter. For example assuming you name your module oftmimetype then like this:

```
<?php
/**
 * Implements hook_file_mimetype_mapping_alter().
 */
function oftmimetype_file_mimetype_mapping_alter(&$mapping) {
  // Add support for oft.
  $mime_type = 'application/x-font-otf';
  // If the mime type does not already exist, add it.
  if (!in_array($mime_type, $mapping['mimetypes'])) {
    $mapping['mimetypes'][] = $mime_type;
  }
  // Get the array index for that mime type and assign the extension to it.
  $mapping['extensions']['oft'] = array_search($mime_type, $mapping['mimetypes']);
  }
}
?>

```
> 4 votes

---
Tags: files, media
---


title: Search only indexing public fields

text:
# Question
Title: Search only indexing public fields
We have a problem with search only indexing fields that have their "Field visibility and permissions" either set to be "Public" or "Custom" with the anonymous user able to view. Any field that is private or has some other custom setting isn't indexed.

I only use Drupal occasionally so I'm far from an expert but as far as I can tell reading around, search should index everything except if it's explicitly told not to.

I've searched around and can't find any setting that would seem to be causing it to behave in this way.

Have I misunderstood how it should behave or is there a setting somewhere I'm missing?

cheers, Gordon

EDIT: I realise that I should have specified that the site is using the Field Permissions module to set the permissions on each of the fields.

# Answer
Drupal renders a node and passes it to indexer. So whatever you see publicly that what is indexed.

but there are few options you can fix that:

1. to render a node for indexing this is called: $build = node\_view($node, 'search\_index'); view mode is search\_index, so in your node template you can check what view mode it is and render it differently.
2. you can use display suite module and then use this display "Search result highlighting input" to configure what is indexed
3. after node is rendered this hook is called $extra = module\_invoke\_all('node\_update\_index', $node); you could implement it and return extra information

hope it helps
> 0 votes

---
Tags: entities, search, users
---


# Question
Title: How to get notified when a user is locked?
After 5 unsuccessful logins, a user gets locked. How can I get notified? I tried with the Rules module without success.

# Answer
You can use Login Security module for D7. It has notifications.

Form the project page :

> A set of notifications by email or Nagios may help the site administrator to know when something is happening with the login form of their site:
> 1 votes

---
Tags: rules
---


title: tabledrag: React on drag event

text:
# Question
Title: tabledrag: React on drag event
I'd like to create a form with tabledrag, with some fancy client-side behavior when (after) a row is being dragged.

More specifically: If row A is being dragged, I want to change an indicators on row B, depending on the new position of row A.

The classical solution would be a jQuery event that fires when a row is dragged. But which event is that, and to which element does it bind?

UPDATE

2pha pointed me to this page, which is nice: http://drupalapi.attiks.com/api/drupal/misc!tabledrag.js/7

So the remaining question is, how to use these commands?

```
$('table#the-table').onDrag(..)

```

would that be it?

# Answer
Got the answer for you! Check out the core tabledrag.js lines 862, 869, 1150, 1160. These are all functions that you can overwrite to react to tabledrag events! Here's a code example I wrote for you:

```
Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
      (function ($) { // Important as this allows $ for jQuery.
        alert('React to tabledrag!');
        return NULL;
      }(jQuery));
    }

```
> 3 votes

---
Tags: javascript
---


title: Right URL rewrite after 404 redirect

text:
# Question
Title: Right URL rewrite after 404 redirect
Is it possible to rewrite the url in a 404 redirect according to the page which is actually being displayed ?

For example, if the non-existent url "/fzenk" is requested, and you have configured the default 404 error page to be the front-page, the url in the address bar after the redirect should be front-page's.

I tried Global Redirect module but it didn't work. Is it possible to do the 404 redirect = URL-rewrite with another module or should we request a new feature ?

---

Update:

While it is possible to do it, it seems to be a bad idea to rewrite 404 pages url.

# Answer
> 5 votes
Thanks to Krister Andersson answer, I seem to have got it right.

```
function THEME_preprocess_page(&$variables, $hook) {
   $status = drupal_get_http_header("status");
   if($status == "404 Not Found") {
      // get the configured 404 error page url :
      $not_found_url = variable_get('site_404');
      unset($_GET['destination']);
      drupal_goto($not_found_url);
   }
}

```

It will rewrite the url according to the configured default 404 error page, it works with multilingual variable too.

# Answer
> 4 votes
If you would like to redirect all your `404` requests to the frontpage I think you could use the `template_preprocess_page()` hook and `drupal_get_http_status()` to check for a 404:

```
function THEME_preprocess_page(&$variables, $hook) {
   $status = drupal_get_http_header("status");
   if ($status == "404 Not Found") {
      header("Location: http://exampel.com/");
      drupal_exit();
   }
}

```

# Answer
> 1 votes
I couldn't seem to get the 403 redirect working with the methods suggested in this thread, so I used a custom menu entry instead, added the path to the native drupal error redirect page, and Bob's your uncle. =o)

```
/**
 * Implements hook_menu().
 *
 */
function MYMODULE_menu() {

  $items = array();

  // On the admin/config/system/site-information form, set the 404 and 403
  // redirects to MYMODULE-custom-error/40x
  $items['MYMODULE-custom-error'] = array(
    'page callback' => 'MYMODULE_custom_error',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );

  return $items;
}

/**
 * Utility function to redirect users to the home page on 404 and 403 errors;
 * note the settings on admin/config/system/site-information
 */
function MYMODULE_custom_error($error) {
  unset($_GET['destination']);
  drupal_goto();
}

```

# Answer
> 0 votes
For **Drupal 6**, here is a slightly modified code:

```
function THEME_preprocess_page(&$variables) {
  $status = drupal_get_headers();
  if(preg_match('/404 Not Found/', $status)) {
    unset($_GET['destination']);
header("Location: /pagenotfound");
    exit;
  }
}

```

Here we couldn't use drupal\_goto() for redirection. Because this results in infinite loop.

---
Tags: 7, redirection, uri
---


# Question
Title: How to put two blocks inline in menu bar
In every theme I tested so far, when a block is added to Menu bar area, each block is always shown stacked in pile, my question is:

> There is a way to to make **two or more blocks** showing **inline** in **menu bar** area?

Please don't say that the question is "too generic", since I tested a plenty of template and they all stack blocks in pile!

Tpl modifications &/or css solutions are both welcome. No scripting please.

# Answer
This is really a question on how to align blocks horizontally in a region, which calls for a CSS solution.

There are a few things to consider before you start:

* Blocks have no defined width. Normally the outer wrapper is just a div, as determined by the block.tpl file, and it is precisely because of this that they take up all the horizontal space given to them. That is why they stack vertically.
* Each theme might be slightly different in handling floats. Some themes are fixed width, some are fluid, some have a built in framework for handling layout, most don't.

For a theme that has a fluid layout without a built-in layout framework, and showing two blocks inline, you can do this:

```
@media screen and (min-width:761px) {
    .region-featured:before,
    .region-featured:after {
        content: " "; /* 1 */
        display: table; /* 2 */
    }

    .region-featured:after {
        clear: both;
    }

    /**
     * For IE 6/7 only
     * Include this rule to trigger hasLayout and contain floats.
     */
    .region-featured {
        *zoom: 1;
    }
    .region-featured .block {
        width:50%;
        float:left;
    }
}

```

This will float two blocks side by side when the overall width is greater than 760px. If you have a fixed width site, then remove the media query. Also note the clearfix styling (when using a layout manager it will just be a class) which ensures that the region wrapper grows vertically to enclose the blocks.

The width of the block was set to 50% because there are two blocks that I wanted to float next to each other (100% / 2 = 50%). For three blocks you will set a width of 33.333333% etc.

When using a layout framework (recommended, and mostly baked into the theme), then it will all just be a matter of assigning proper classes, so you would then need to assign a region-class in the page template to the region, and assign classes to the blocks, perhaps using a module like Block Class, or also inside the block or region template file.

For a theme with a baked-in layout framework, look at Bootstrap, amongst numerous others. It is extremely easy to use, but you must familiarise yourself with the official bootstrap documentation. Bootstrap is not Drupal specific. It is just a framework that the Drupal Bootstrap theme developers adopted.

For more CSS solutions on aligning Divs horizontally, How to Align Divs Horizontally in CSS
> 1 votes

---
Tags: routes, blocks, theming
---


# Question
Title: Show node field as a carousel using jCarousel module programmatically?
I have a content type with a fiel called: **fotos-carousel** (image type) which I want to show as a carousel. I can't use views to do this.

I installed the jcarousel module and read the documentation to add a carousel programmatically.

Then I create a tpl file to change the output of this field: **field--field-fotos-carousel.tpl.php**

and add this code:

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php foreach ($items as $delta => $item) : ?>
  <?php
    $items_carousel[]='<img src="sites/default/files/'.$item['#item']['filename'].'" width="75" height="75" alt="" />';
  ?>
<?php endforeach; ?>
<?php
            $options = array ('visible' => 1,'scroll' => 1,);
            print theme('jcarousel', array('items' => $items_carousel, 'options' => $options));
            jcarousel_add('.jcarousel-id-1', array('vertical' => TRUE));
        ?>

```

The output (ul, li, images) is fine but the carousel is not loaded (jquery)

Anyone has done this before? What am I missing?

# Answer
Have you try with this module: http://drupal.org/project/field\_slideshow It will help you to build a carousel with the content of a field.

As field slideshow is not the best options, because you need field collection.

Another option is this other.

Use a normal image field. Build a block view with the images from the node. With Display suit, you can choose what fields you can show or hidden, you can hidden the imagefield. And also use Display Suit (admin/structure/ds/fields) to become the views block as a field for the content type.

The last step is to enable the new field.
> 0 votes

# Answer
You can combine EVA (Entity Views Attachment) and Flexslider to achieve this.

1. Create a new view
2. Add an EVA display
3. Select your bundle and content type
4. Add `Content:nid` as as contextual filter, provide the default `Content ID from URL`
5. Add your content type as filter, and add the image field you want.
6. Under the multiple results field, uncheck the option that shows them all in one line.
7. Set the format to `Flexslider`, and choose the Flexslider settings you want to use.

Under the settings, just look at the Flexslider example and use the carousel settings. Not only does Flexslider perform better in general the Field Slideshow, but it also gives you a lot of flexibility when it comes to theming.
> 0 votes

# Answer
Try jQuery Carousel module. It provides **Views Style Plugin** and **Field Formatter Plugin** both. It also provides an option to use the horizontal and vertical carousel.
> 0 votes

---
Tags: javascript
---


# Question
Title: Create a wrapper around specified number of fields in views
I like to wrap 3 elements of a view in a div. I got this code, but it doesn't seem to work. It keeps printing the div but never the /div which makes everything nested in the previous row.

```
<?php if($i % 3 == 0){ print '<div class="row">'; } ?>
<?php print $row; ?>
<?php if($i % 3 == 2){ print '</div>'; } ?>

```

Any suggestions?

# Answer
> 0 votes
Semantic Views module will let you configure HTML output easily.

# Answer
> 0 votes
I found the solution.

```
<?php $i = 0; foreach ($rows as $id => $row): ?>
<?php if($i % 3 == 0){ print '<div class="row">'; } ?>
<?php print $row; ?>
<?php if($i % 3 == 2){ print '</div>'; } ?>
<?php $i++; endforeach; ?>

```

I forgot to define $i before foreach en $i++ before endforeach.

---
Tags: views
---


title: Loading a Taxonomy Term form for a user

text:
# Question
Title: Loading a Taxonomy Term form for a user
I have a User Profile page that loads specific taxonomy terms (associated with a user account and its form, `user_profile_form`) to filter specific content with. I've tried to implement these forms independent of any user profile form logic, but its troublesome to work around this logic.

This is further compounded by the fact that all this behavior is essentially split across a ctools\_wizard form, since this component ties in a multi-page/multi-form process.

Is there a way I can load in these specific fields, inherited from user\_profile\_form, into a new form and have those changes save within that form, or is there an entirely separate approach to use here?

# Answer
If you want to pass variables to a form you can. See this similar post.

Just add $vars as second argument.

```
drupal_get_form('new_form', $vars);

```

and...

```
function new_form($form, &$form_state, $vars) {

```

If you are trying to pass the user object to user\_profile\_form you can do it like so:

```
global $user;
$form_state = array();
$form_id = 'user_profile_form';
$args = array($user);
$form_state['build_info']['args'] = $args;
form_load_include($form_state, 'inc', 'user', 'user.pages');
print render(drupal_build_form($form_id, $form_state));

```

If you really want to load the user\_profile\_form inside another form (?) as suggested in your comment, you can do the snippet above but not render the form, just load it into an a variable and extract vars from it.

```
$loaded_profile_form_with_user = drupal_build_form($form_id, $form_state);

```
> 0 votes

---
Tags: 7, taxonomy-terms, chaos-tool-suite
---


title: How to create a custom handler in view?

text:
# Question
Title: How to create a custom handler in view?
I am trying to alter a field's argument handler. But It is showing me `broken/missing` handler in view's argument. I have tried it in following ways :

I am adding the following two code block in `hook_field_views_data_alter` where :

```
$table_name = node__field_test;
$field_col = field_test_value;

```

I want to change handler for a field.

First method by reviewing time spent module's code :

```
$data[$table_name][$field_col]['argument']['id'] = 'MyClassName';

```

I didn't understand the concept of `id` above and how it will recognise the class of my module?

Second method as in D7 :

```
$data[$table_name][$field_col]['argument']['handler'] = 'MyClassName'; // Second

```

How It works in D8?

# Answer
The id is a plugin ID. You either need to define your own views argument plugin and change the id to that or alter the plugin definition and replace the class there.

The first will just update a specific field, the second would replace the plugin everywhere where it is used.
> 2 votes

---
Tags: 8, views
---


title: views webform submission username

text:
# Question
Title: views webform submission username
I would like to have webform submission username using views. Add fields \> webform submissions: user The result is uid (user id number)

How can I have username login name instead of uid ?

# Answer
> 1 votes
'Username' as a field is not available to webform as it is not stored in the webform submission.

You need to add a Relationship to the User using the UID and then the User Name will be available to you in the fields section.

See more about relationships in this video

---
Tags: views, webforms
---


title: Creating muliple nodes from one page

text:
# Question
Title: Creating muliple nodes from one page
I want to create multiple nodes from one page where I input one or two values into each entity, where each of the entities has a reference.

Example: If I had three kids, I would measure their height each week, entity types "kid" and "height". Height references to kid and instead of click add "height" three times and select which kid then input height, I would like to have a page with the names (or ID) of the kids, then one input field for each, so that when I save, three entities of height are created with the values specified.

# Answer
> 0 votes
There are a couple of modules to create entities (nodes etc) inline i.e in the parent form, when it's being created itself.

When you save the form, it creates the entity AND the entities that are referencing it, but it's up to you to create the entity structure and references to achieve what you want.

I can vouch for References Dialog

**However**, I think you are making it too complex and you only really want one node type (kids) with an unlimited field (height), if that is your real scenario.

For example you easily create a custom form with three (or loop for x) fields and when it saves it adds the result to existing nodes, eg :

```
// Get and render the form somewhere.
$form = drupal_get_form('kids_height_form');
print render($form);

/**
 * Form constructor.
 */
function kids_height_form() {
  $kids = array(2210, 2043, 2038);
  $entities = entity_load('node', $kids);
  // dpm($entities);
  foreach ($entities as $kid) {
    $id = $kid->nid;
    $form["height_$id"] = array(
      '#title' => 'Height this week for $id',
      '#type'  => 'textfield',
    );
  }
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

/**
 * Form submit handler for kids_height_form().
 */
function kids_height_form_submit($form, &$form_state) {
  $kids = array(1, 2, 3);
  $entities = entity_load('node', $kids);
  foreach ($entities as $kid) {
    $id     = $kid->entity_id;
    $height = $form_state['values']["height_$id"];
    $count  = count($kid->field_height[LANGUAGE_NONE]);
    $kid->field_height[LANGUAGE_NONE][$count + 1] = array('value' => $height);
    entity_save('node', $kid);
  }
}

```

The top bit prints the form, the form constructor simply create as many text fields as there are node ids in the array and the submit handler does the same loop except also adds the result to a new delta for the height field and saves the entity.

You can also achieve this with EntityMetaWrappers and may be a bit neater but the process is very similar. (this is untested by the way and will need work to suit your needs);

---
Tags: entities
---


title: How to install eComma with Panelizer?

text:
# Question
Title: How to install eComma with Panelizer?
I want to install the eComma 7.x-1.x Drupal module, providing word-wise annotation features. However, its installation instructions do not work in my environment, probably because I have also Panelizer installed and something has to be done different then.

# Answer
> 1 votes
These instructions integrate the eComma 7.x-1.x installation instructions, but with your requested modifications to make them work with Panelizer.

1. Create a basic installation of Drupal for your local development. You need to use MySQL / MariaDB as your database, eComma won't work with PostgreSQL at the moment \[reason\].
2. Install eComma (assuming you use drush, which is a great tool for Drupal developers …):

```
drush dl ecomma
drush en ecomma

```
3. If you want to install the module in a way that allows you to contribute back with Github pull request, replace the content of the eComma module with the Github repository's 7.x-1.x branch:

```
cd <your_docroot>/sites/all/modules/;
rm -R ecomma/*;
git clone "https://github.com/coerll/eComma.git" -b 7.x-1.x --single-branch ./ecomma

```
4. Install the patch mentioned in the eComma README. It fixes Community Tags' Drupal issue #2193175, which otherwise leads to Server Error 500 on node view pages (`/node/<some-node-id>`).

```
cd sites/all/modules/community_tags
wget "https://www.drupal.org/files/issues/community_tag_tagadelic_d7_fix-2193175-4.patch"
patch -p1 <"community_tag_tagadelic_d7_fix-2193175-4.patch"
rm "community_tag_tagadelic_d7_fix-2193175-4.patch"

```
5. Go to "Administration → Configuration → Search and metadata → Clean URLs" (`/admin/config/search/clean-urls`) and select "Enable clean URLs".
6. Go to "Structure → Taxonomy → Add Vocabulary" (`/admin/structure/taxonomy/add`) and add a vocabulary.
7. Add or edit the custom content type that you want to use eComma on.
8. In the edit form of that content type, go to the horizontal tab "Comment settings" and set "Preview comment: Optional".
9. Go to "Manage fields" for your content type (`/admin/structure/types/manage/content-type-name/fields`) and add a new field.

1. Use field type "Long text" (it will only work with that, not with "Long text and summary").
    2. Go to the field settings. If you problems doing so (like "*Notice: Undefined index: instance in ecomma\_form\_alter() (line 351 of …/ecomma.module).*", you can manually enable eComma for the field in the database instead of doing the next two steps. You would use a query like:

    ```
    INSERT INTO ecom_ecomma_field_enabled (field_name, content_type_name, ecomma_enabled)
    VALUES (''your_field_name", "your_content_type", TRUE);

    ```
    3. In the field settings, use "Number of value: unlimited" (though that's probably not obligatory).
    4. In the field settings, select "Enable ecomma commentary features", right above the "Save settings" button.
10. Again, go to "Manage fields" for your content type (`/admin/structure/types/manage/content-type-name/fields`) and add a new field of field type "Term reference", using the "Autocomplete term widget" and selecting your Vocabulary from the field settings.
11. Go to "Configuration → Content Authoring → Community tags" and select "Enable community tagging" for the new vocabulary that you created.
12. Go to "Configuration → jQuery update → jQuery and jQuery UI CDN" and select "None".
13. Edit your eComma content type again, there go to the horizontal tab "Community tags settings" and select "Community tagging form: Block".
14. Go to "People → Permissions" and

1. Check "Community Tags: tag content" for authenticated and anonymous users. This will also enable unauthenticated users to see the tags, but not to tag.
    2. Check "Community Tags: edit own tags" for authenticated users.
    3. Check "Comment: view comments" for anonymous and authenticated users. This will enable unauthenticated users to see the comments, but not to comment.
15. Configure Drupal to show the "Long text" text field of your new content type, plus various eComma blocks, when somebody views a node of that content type. Depending on what layout mechanism you use (vanilla Drupal, Panels / Panelizer, Display Suite, context etc.) this will be different. Here's how to do it for Panelizer:

1. Go to "Administration → Structure → Pages", enable "Node template" and edit it.
    2. In the node template, create a new variant of type "Panel", with the optional feature "Selection rules".
    3. Add a new selection rule for your new variant, and doing so choosing "Node: type" from the dropdown list and later the content type(s) which you want to use with eComma.
    4. Go to the "Content" section of your new variant, click a gear icon where you want to add content, choose "Add content" from the dropdown.
    5. In the content selection dialog, go to the "Node" tab and select the Long Text type field you want to use eComma on (it starts with "Field: …" in this list). The eComma annotation dialog will not appear if you add this field as part of an aggregate, like by putting in the full rendered node with this dialog!
    6. Click the gear icon again, click "Add content", and now from the Miscellaneous tab of the dialog, one by one, add the "Community tagging form" block and all blocks starting with "eComma". Normally these blocks are nicely integrated into overlapping tabs in eComma, but I could not yet find out how to achieve this with Panelizer. The "Community tagging form" block is needed because if not adding it, it will not appear as part of the JavaScript tagging form either!
    7. Save this all.
16. Test your setup.

1. Create a node of your new content type.
    2. Enter some text in the "Long text" text field – not in the "Body" text field. And save.
    3. View the node and select text with mouse cursor to start annotating it.

---
Tags: installation, panels
---


# Question
Title: wysiwyg ckeditor inline styling not working
I'm using wysiwyg api with ckeditor, but I can't make it to use inline styles like when I use indent from editor, it actually drops the style (which is margin-left) in output. it's not an override, it actually doesn't even appear in the code when I inspect it.

# Answer
Verify the `format` used by the `body` field. If you are using `Filtered HTML`, filtering is done before rendering it on the page, where all inline styling is removed.

You could either set your format on `Full HTML` (which doesn't filter the body) or use the WYSIWYG Filter module which allows to enable certain inline styles on the `Filtered HTML` format.
> 0 votes

# Answer
If Mike's solution is not working, then check my answer and see if that fits your situation.

I know for a fact that Wysiwyg with CK Editor had several problems in it's integration with Media, but a fix was release a few days which actually applies the styling.

So previously, when I used to click on an image, and change it's width and height. It would look in wysiwyg, but on clicking source code, I could not see it on inspection, and it would again look like the original on wysiwyg. Your problem sounds similar, so I'm pointing you towards the wysiwyg and ckeditor fix. Tell me if that worked for you

a) Media + Wysiwyg -: https://drupal.org/comment/8009717#comment-8009717 b) Wysiwyg + Ckeditor -: https://drupal.org/node/1956778 (patch 37)

Need to both if it's' with Media, else just the latter. Please test on local before you apply on server.
> 0 votes

# Answer
I know it's a relatively old question, but I found myself in a similar situation today, so maybe the solution I found will be of use to somebody else.

In my case, it appears that the problem came from CKEditor itself, which apparently implemented a new feature related to code cleaning, starting with version 4.1. (It's called Advanced Content Filter (ACF), and there's a discussion about it here: https://www.drupal.org/node/1956778) The current **stable** version of the wysiwyg module (which hasn't been updated for more than two years) doesn't take that into account, which means the user can't disable this feature.

The solution is simple: install the dev version of the wysiwyg module. It provides a new option that allows the user to disable or customize CKEditor's AFC.
> 0 votes

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


# Question
Title: Difference between .info files hook_menu() file key?
What is the difference between declaring the files\[\] in a module's .info file and declaring the file inside a hook\_menu() item?

According to the Drupal Documentation on .info files...

> When a module is enabled, Drupal will rescan all declared files and index all the \>classes and interfaces that it finds. Classes will be loaded automatically by PHP \>when they are first accessed.

And the documentation on the files key for hook\_menu() is...

> A file that will be included before the page callback is called; this allows page \>callback functions to be in separate files. The file should be relative to the \>implementing module's directory unless otherwise specified by the "file path" \>option.

This sounds a little redundant to me. Aren't the files being "included" when you declare them in the .info file? So why would i need to list the file location for a function inside hook\_menu when it should already be included?

# Answer
I'm sorry you do not understand my question, however, I believe the question was pretty straightforward. After discovering some interesting articles I think worked out my confusion.

The files\[\] entry in the module .info file is not used for "including" php files. It is meant only to auto load your classes and interfaces for your application (if you're writing your module using object oriented methodologies). It could be thought of as the "import" statement in Java.

The following articles go more into detail about PSR-0 standard and auto loading in php. previousnext.com.au/blog/drupal-8-now-psr-0-code-drupal-7/ riceball.com/d/book/export/html/1200

That being said, the purpose of the file key inside the hook\_menu() $item\[\] is to specify where the file containing the page\_callback function exists. If your page\_callback function is defined inside a class (statically), then you do not have to provide the file and filepath keys. The callback would look something like this, 'page\_callback' =\> array('MyClass::myfunction');

For more information on OO Page callbacks in Drupal 7, read the following article. previousnext.com.au/blog/object-oriented-page-callbacks-drupal-7

If your page\_callback is not inside a class, but just inside a file then you'll need to provide the file and filepath keys so that Drupal can include this file when your page is created.
> 1 votes

# Answer
in files from .info it scans for classes and interfaces. When you use class somewhere in code, file is included automatically. You don't need to include it

In hook\_menu you define in which file your callback function is.

not sure how is it redundant. how would you be able to switch one with another?
> 0 votes

---
Tags: 7, routes, .info
---


title: JS compression ratio in Advagg module

text:
# Question
Title: JS compression ratio in Advagg module
I am trying to use AdvAgg in my Drupal 7 site. I am using a local server for running tests.

The issue is that the module doesn't compress (php-jsmin) all the JavaScript files, which is causing a bad score in page speed insights.

After some debugging, I found out the problem: The uncompressed file didn't have a compress ratio between 0.1 and 0.9 so it was being aggregated as it was.

I'm talking exactly about advagg\_js\_compress.module file, lines below 143:

```
// Set to "-2" if compression ratio sucks (it's already compressed)

```

Why is necessary a min ratio? Could set min ratio to 0 so that all JavaScript files are processed?

# Answer
Sometimes things compress too well; ie empty string. Sometimes things don't compress at all; ie already compressed. In both cases I opt to use the original file since minification of already minified js can sometimes cause js errors. You can variable set it if you want to adjust the min/max cutoff.
> 2 votes

---
Tags: 7, css-js-aggregation
---


title: How to Change block.tpl.php

text:
# Question
Title: How to Change block.tpl.php
I created my own bootstrap sub theme and wondering how can I edit the following line:

```
<h2<?php print $title_attributes; ?>><?php print $title; ?></h2>

```

to

```
<h3<?php print $title_attributes; ?>><?php print $title; ?></h3>

```

As you can see, I want to change the h2 tag to h3 tag.

The code above can be found under `bootstrap/theme/block`. But I believe that it's not a good idea to edit it directly on this location, unless I'm mistaken.

I know that `html.tpl.php` or `page.tpl.php` can be copied from `bootstrap/theme/system` folder to `mytheme/templates` but wondering how can I do the same with `block.tpl.php`.

Any ideas?

Note: I'm using bootstrap 3.0.

# Answer
> 3 votes
Copying the template file from the bootstrap theme to your subtheme, and making the changes in the subtheme should work just fine.
Just note to clear the caches.

---
Tags: 7
---


# Question
Title: form_state['values'] generating error undefined index: values
I am having a simple form like this. I want to read the ID value in the middle of the form. When I try to get it using `$fromvalues = $form_state['values']['id'];` it gives the following error:

> Undefined Index: values in `templates_form()`

```
function templates_form_add($form, &$form_state, $templates = NULL) {
  $templates = entity_get_controller('templates')->create();
  return templates_form($form, $form_state, $templates);
 }

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

   $form['id'] = array(
     '#title' => t('ID'),
     '#type' => 'textfield',
     '#default_value' => isset($templates->id) ? $templates->id : '',
     '#description' => t('Unique Id'),
     '#required' => TRUE,
     '#maxlength' => 255,
     '#disabled'=> empty($ntemplates->id) ? FALSE : TRUE,
   );

   $fromvalues= $form_state['values'];

   $form['city'] = array(
     '#title' => t('city'),
     '#type' => 'select',
     '#options' => $cities,
     '#default_value' => isset($templates->city) ? $templates->city: '',
     '#required' => TRUE,
     '#maxlength' => 255,
     '#disabled'=> empty($templates->id) ? FALSE : TRUE,

   ),

```

# Answer
> 0 votes
The error indicates precisely what is going on: during the initial call of `templates_form()` the `$form_state['values']` does not yet exist. This will exist in a future ajax call (if you do ajax) and in validate and submit functions. You better check if it exists first with `isset` or `empty`.

---
Tags: 7
---


# Question
Title: Registration form to be submitted via ajax
I want to submit drupal'S registration form to be submitted via ajax .How can I acomplish this???

# Answer
> 1 votes
You need the *Ajax submit for any form* module, here:

https://www.drupal.org/project/asaf

---
Tags: ajax
---


# Question
Title: Why does the same Rule Calculating The Sell Price Of A Product fire multiple times?
I'm having dreadful performance with Commerce Kickstart 2. Trying to troubleshoot.

I noticed that when viewing any Product in the catalog, the Rules Evaluation log looks like the log below.

Questions: 1. Why is the event Calculating the sell price of a product firing multiple times?

2. Why is the rule "Apply a discount to a given order" firing? The product I'm viewing has nothing to do with the reaction rule or the cart?

This adding a lot of unneeded overhead, right? How do I stop it?

`0 ms Reacting on event Calculating the sell price of a product.
 7.329 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
 7.698 ms The condition data_is_empty evaluated to FALSE [edit]
 7.903 ms The condition entity_has_field evaluated to TRUE [edit]
 8.669 ms The condition data_is evaluated to FALSE [edit]
 8.676 ms AND evaluated to FALSE.
 8.694 ms Finished reacting on event Calculating the sell price of a product.`

````
0 ms Reacting on event Apply a discount to a given order.
0.256 ms Evaluating conditions of rule 10% Of AH-10. [edit]
0.854 ms The condition commerce_order_contains_products evaluated to FALSE [edit]
0.862 ms AND evaluated to FALSE.
0.876 ms Finished reacting on event Apply a discount to a given order.
0 ms Reacting on event Calculating the sell price of a product.
0.164 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.317 ms The condition data_is_empty evaluated to TRUE [edit]
0.324 ms AND evaluated to FALSE.
0.336 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.376 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.656 ms The condition data_is_empty evaluated to TRUE [edit]
0.673 ms AND evaluated to FALSE.
0.7 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.223 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.407 ms The condition data_is_empty evaluated to TRUE [edit]
0.42 ms AND evaluated to FALSE.
0.439 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.221 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.384 ms The condition data_is_empty evaluated to TRUE [edit]
0.393 ms AND evaluated to FALSE.
0.418 ms Finished reacting on event Calculating the sell price of a product.

0 ms Reacting on event Calculating the sell price of a product.
0.398 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.67 ms The condition data_is_empty evaluated to TRUE [edit]
0.687 ms AND evaluated to FALSE.
0.714 ms Finished reacting on event Calculating the sell price of a product.

````

# Answer
> 0 votes
This is because the price is calculated during preparation for display where the field is rendered on the page, for the Add to Cart form to determine product availability, and for recalculation of any instance of that product in your cart. I believe we tried caching calculated prices in the product entity at one point in time to avoid duplicate calculation, but that obviously didn't stick. I don't have a solid recommendation here, just wanted to provide the info requested. Also, note that cart price refreshing is adjustable but is intended to happen in realtime with the full cart context. I'd think you could safely find a way to eliminate the duplicate calculation between the price field and cart form, but you'd want to do it without interfering with the cart refresh.

---
Tags: rules, commerce
---


# Question
Title: How do I apply check_markup() as Twig filter?
I am trying to modify output in my twig file. In D7, I was able modify data in my array with this

```
check_markup($tweet->text, 'full_html');

```

and I see that this function still exists in D8. However, I'm not sure how I would use this in a filter in twig. This is what I have so far:

```
{% for tweet in params.tweets %}
<div class="tweet-wrapper">
<div class="tweet-profile-image">
    <img src='{{ tweet.user.profile_image_url }}'/>
</div>
<div class='tweet-text'>
    <!--check_markup($tweet->text, 'full_html');-->
    {{ tweet.text }}
</div>

</div>
{% endfor %}

```

I actually tried to do this before I sent it to the template as well, but it didn't change anything:

```
 foreach($tweets as $tweet) {
  $tweet->text = check_markup($tweet->text, 'full_html');
  $cleanTweets[] = $tweet;
}
dpm($tweets);
$params = array('tweets' => $cleanTweets);
$tweet_template = array('#theme' => 'twitter_pull_tweet_listing', '#params' => $params);
return $tweet_template;

```

What I'm trying to do here is make drupal create links for web links in the twitter tweet text. This worked fine for me in D7.

# Answer
> 4 votes
First of all, what is the motivation here? Are you getting double escaping or something? Providing more background information may help to get you a better answer.

Before we get too much further, relying on a certain configuration of the `full_html` text format seems like it's not a good solution. For example, to get the below to work for automatically creating links for this scenario, I had to enable **Convert URLs into links** in the `full_html` text format.

If you take a look at the documentation for `check_markup()` you'll see this note:

> Note: this function should only be used when filtering text for use elsewhere than on a rendered HTML page. If this is part of a HTML page, then a renderable array with a #type 'processed\_text' element should be used instead of this, because that will allow cache tags to be set and bubbled up, assets to be loaded and #post\_render\_cache callbacks to be associated. In other words: if you are presenting the filtered text in a HTML page, the only way this will be presented correctly, is by using the 'processed\_text' element.

So based on that I think what you may want to do is in your block build method create a 'processed\_text' element (render array):

```
foreach ($tweets as $tweet) {
  $cleanTweets[] = array(
    '#type' => 'processed_text',
    '#text' => $tweet->text,
    // Relying on the full_html text format to do certain things is probably
    // not a good idea.
    '#format' => 'full_html',
    // Potentially add keys for #filter_types_to_skip and #langcode.
  );
}
$params = array('tweets' => $cleanTweets);
return array('#theme' => 'twitter_pull_tweet_listing', '#params' => $params);

```

Then you can do this in your Twig template (`twitter-pull-tweet-listing.html.twig`):

```
{% for tweet in params.tweets %}
  …
  {{ tweet }}
  …
{% endfor %}

```

To relate this to Drupal 7, that Twig template code would be roughly equivalent to running `render()` on each array element (individual render array) in the `$cleanTweets` array.

If you're more interested in creating an actual Twig filter, the Twig documentation has some information on that, and Symfony has some very comprehensive documentation that matches up with how you would create a Twig extension in Drupal 8.

---
Tags: 8, theming
---


title: Removing text from the Drupal interface

text:
# Question
Title: Removing text from the Drupal interface
I remember in Drupal 6 there was a module that did text substitution easily (from text that appeared anywhere in the interface). Does that exist in Drupal 7? I just want to remove the word "From" everywhere it appears on this Drupal commerce site: http://hum.homedns.org:8888/acmefilterbags2/product-category/featured-kits thx!

UPDATE: I tried String Overrides, thought that would do it, but did not. Any ideas?

# Answer
> 1 votes
I think it's not a text of Drupal Interface.

Add `.price_prefix { display: none }` to your theme's css file and it will **disappear**.

# Answer
> 1 votes
The css that @herci suggested was what I was going to suggest from your title but reading your description I doubt that would work as the likely of one word having it's own class is limited. So I can suggest three methods:

1. Use the development version of Scanner for D7; I haven't used it and it *could* be dangerous - so definitely back up your database!
2. Directly access your DB through cmd line (not all hosts offer that ability) or access your DB through PHPMyAdmin (again not all hosts offer that but *most* shared hosts do and if you have a private host you can usually install it yourself. Then browse the database and find which tables have 'from' that you want to remove - and then regex replace them. I don't actually recommend this as it has a **high chance of damaging your install** so if you do this definitely back it up.
3. Add a jQuery script: jQuery ReplaceText and add your own custom script something like this:

`(function($) {
 $('#content p').replaceText( /\bfrom\b/gi, '' );
}(jQuery))`

That will replace any instances of from in any paragraph elements inside an element with the id of content. You'll probably need to adjust that selector. This method has some advantages and disadvantages; it isn't actually changing your site, it just changes the appearance on load. So it can be slow but it is pretty *safe* unlike the other two methods.

---
Tags: 7
---


title: Forum lay out problem

text:
# Question
Title: Forum lay out problem
I'm having some problems with my forum, I messed up my lay out and can't seem to get it back. Reinstalling the Advanced Forum module doesn't help.

Does anyone know how to get my text to the right, in other words next to the red line I drew? Also it doesn't register my 'enter' clicks, so a reply is just plain text without structure.

Thanks

# Answer
In Chrome right click on the text and choose 'inspect element'. Find the css selector for that element. Then go into the stylesheet for your theme, and add a rule there to add margin-left to the text.

It sounds like it might be a javascript problem if you can't click a certain link. Check javascript errors in the console.
> 1 votes

# Answer
In regards to the new lines not working the most likely problem is that you are using a filtered html text mode and that `<p>` and/or `<br>` are not accepted tags. Set it to full HTML or a filtered text mode which accepts paragraph and break tags.
> 0 votes

---
Tags: nodes
---


# Question
Title: Is it safe and fine to block external access to sites/all/modules folder and all its subfolders and files?
That's to say block all except 127.0.0.1?

# Answer
> 1 votes
If you are talking about blocking HTTP access (for browsers), then it won't give you any additional security.

But if you nevertheless want to do so, then exclude `*.css`, `*.js` and all images from being blocked.

---
Tags: security
---


# Question
Title: Drupal + Solr, how to boost search results with updated date?
I'm trying to boost search results to give more relevancy to newly updated / created content. What I have tried is to use the following:

```
/**
 * Implementation of hook search_api_solr_query_alter
 */
function mml_search_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  // Boost by changed date. Fresher to top.
  $call_args['params']['freshness'] = 'recip(abs(ms(NOW/HOUR,ds_changed)),3.16e-11,10,1)';
}

```

But it doesn't seem to have any effect.

Any help would be appreciated.

Here is screenshot of solr admin side of the "field" Im trying to boost http://monosnap.com/image/A3c6WOGi71z0Smeke8tYgBbnoeNkyK

# Answer
> 2 votes
This module may be a solution https://www.drupal.org/project/search\_api\_sorts

Otherwise using you method above - According to this post http://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results

then you need to add an extra \[\]

```
$call_args['params']['freshness'][] = 'recip(abs(ms(NOW/HOUR,ds_changed)),3.16e-11,10,1)';

```

However after testing I still can get the result I want.

For example the value 3.16e-11,10 ; as far as I understand it means a year of milliseconds that gives a score of 10 inside that time span. and then decrease after.

For testing I used

```
call_args['params']['qf'][] = 'recip(abs(ms(NOW/HOUR,ds_changed)),86400000,21,1)';

```

which should give Posts added/changed on the day a score of 21 and then decreases daily.

Testing with 3 identical listings. And only title set at a boost rate over 1. I cannot get the articles to listing in date. order. Have i missed something obvious.

# Answer
> 1 votes
In hook\_apachesolr\_query\_prepare,add ur indexed field with ur weightage using param **`bf`**.
This hook is similar to the query\_alter but runs before the query is cached

Reference to parameters https://cwiki.apache.org/confluence/display/solr/Common+Query+Parameters

```
  /**
     * Prepare the query by adding parameters, sorts, etc.
     *
     * This hook is invoked before the query is cached. The cached query is used
     * after the search such as for building facet and sort blocks, so parameters
     * added during this hook may be visible to end users.
     *
     * This is otherwise the same as HOOK_apachesolr_query_alter(), but runs before
     * it.
     *
     * @param object $query
     *  An object implementing DrupalSolrQueryInterface. No need for &.
     */

function module_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
     $query->addParam('bq','indexedFieldName^20');
     watchdog("solrquery", '<pre>' . print_r( $query, true) . '</pre>');
}

```

I have used

```
 $query->addParam('bq','tm_display_name^20');

```

bq: Boost Query: specifies a factor by which a term or phrase should be "boosted" in importance when considering a match.

Where solrquery obj results like that

```
   [bq] => Array
                (
                    [0] => tm_display_name^40
                )

```

Assuming that field is already indexed in our solr.

Use that hook. Then search for a content. In recent log message 'solrquery',check whether your field is added in bq

Have added the link for you reference. http://www.computerminds.co.uk/articles/boosting-solr-search-results-query-time

---
Tags: 7, hooks, search
---


# Question
Title: Does Drupal 7 support connecting to DB using MySQLi?
I have tried to connect to Mysql DB using Mysqli by declaring *'driver' =\> 'mysqli'* inside DB array in settings.php but I get the following error:

```
Warning: require_once(/srv/http/my-domain/includes/database/mysqli/database.inc): failed to open stream: No such file or directory in /http/www/my-domain/includes/database/database.inc on line 1688

```

Thanks.

# Answer
> 2 votes
No. Drupal 7 does not come with Mysqli support. It only comes with PDO based drivers for MySQL, pgSQL and SQLite.

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

https://www.drupal.org/requirements/pdo

See the files :

* INSTALL.mysql.txt
* INSTALL.pgsql.txt
* INSTALL.sqlite.txt

to find out more about how to install using each option.

There are also many community provided solutions for connecting to other databases including MsSQL, Mongo and Oracle.

Have a look at the Drupal modules page for more information on database drivers

The core advantage of PDO over MySQLi is in its database driver support. PDO supports 10+ different drivers, opposed to MySQLi, which supports MySQL only.

If you are interested in the comparison between PDO and Mysqli there are many articles around including this one.

---
Tags: database, configuration
---


title: Varnish 4.0 vcl for Drupal 7

text:
# Question
Title: Varnish 4.0 vcl for Drupal 7
Drupal7, Varnish 4.0, Ubuntu 12.4

Varnish is installed an working, but returning intermittent 503, I think whenever Varnish goes to the backend. Even though the request returns 503, a page refresh may return 200, HIT from cache. Another refresh may be 200 or 503. I think a subsequent 503 is a HIT-FOR-PASS.

We've opened up the timeouts, as follows:

```
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "8080";
.probe = {
.url = "/ping";
.timeout = 600s;
.interval = 600s;
.window = 5;
.threshold = 2;
}
.first_byte_timeout = 900s; # How long to wait before we receive a first byte from our backend?
.connect_timeout = 500s; # How long to wait for a backend connection?
.between_bytes_timeout = 200s; # How long to wait between bytes received from our backend?
}

```

So I suppose it's not that Varnish is timing out in a blink of the eye.

Probably the problem is in the vcl; this is what I'm using: https://github.com/mattiasgeniar/varnish-4.0-configuration-templates/blob/master/default.vcl

Here are fragments from the varnish log for 3 successive calls to the same page: 503, then 200, then 503 again:

```
First call - returns 503
-   VCL_call       BACKEND_FETCH
-   VCL_return     fetch
-   FetchError     no backend connection
-   Timestamp      Beresp: 1408509130.524000 0.000219 0.000219
-   Timestamp      Error: 1408509130.524013 0.000232 0.000013
-   BerespProtocol HTTP/1.1
-   BerespStatus   503
-   BerespReason   Service Unavailable
-   BerespReason   Backend fetch failed
-   BerespHeader   Date: Wed, 20 Aug 2014 04:32:10 GMT
-   BerespHeader   Server: Varnish
-   VCL_call       BACKEND_ERROR
-   BerespHeader   Content-Type: text/html; charset=utf-8
-   BerespHeader   Retry-After: 5

```

Page refresh - Returns 200 from the cache VCL\_return hash \- VCL\_call HASH \- VCL\_return lookup \- Hit 2147745802 \- VCL\_call HIT \- VCL\_return deliver \- RespProtocol HTTP/1.1 \- RespStatus 200 \- RespReason OK

Another refresh - returns 503 again.

* VCL\_call HASH
* VCL\_return lookup
* Debug "XXXX HIT-FOR-PASS"
* HitPass 2147811368
* VCL\_call PASS
* VCL\_return fetch
* Link bereq 196777 pass
* Timestamp Fetch: 1408509419.224633 0.000666 0.000666
* RespProtocol HTTP/1.1
* RespStatus 503
* RespReason Backend fetch failed

Any clues on getting the vcl correct appreciated.

# Answer
The VCL you have linked to and your example in the question show you only using one backend. In this case using the probe to do a health check serves no purpose. As per drifteaur's answer disabling probe resolves many 503 issues and as you have no need for it, problem is solved.

However, if you are testing working towards rolling out on multiple backends then it still needs to be fixed(understood).

Looking at the VCL you linked (https://github.com/mattiasgeniar/varnish-4.0-configuration-templates/blob/master/default.vcl) it uses many sections which have been taken from https://www.varnish-software.com/ so we can presume (hopefully) that they are correct.

Currently, your probe is checking the response from "/ping" at your host and port, 127.0.0.1:8080, so that is 127.0.0.1:8080/ping .

If your set-up is multiple virtualhosts on one server with varnish sitting infront then using probe like this will not get a response(as this full url has most probably not been configured) and in turn this will lead to the backend being marked as "sick / unhealthy" and a 503 will be produced as Varnish will not even attempt to access the backend.

To confirm that it is your server setup add the following to your probe

```
backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .probe = {
              .request =
              "HEAD / HTTP/1.1"
              "Host: www.EXAMPLE.com"
              "Connection: close";
              }
}

```

You will need to change www.EXAMPLE.com to a real domain you are using on the server.

If this gives you 200s rather than 503s than it is safe to confirm that using probe as you were with your server set-up was incompatible.

Probes info: https://www.varnish-cache.org/docs/trunk/reference/vcl.html#reference-vcl-probes
> 1 votes

# Answer
I had the same problem (503) with the same example config and Drupal. I resolved it by commenting out the .probe part of the backend configuration. Not sure why that helped though.
> 0 votes

---
Tags: proxies
---


title: Problem with a query

text:
# Question
Title: Problem with a query
On **Drupal 8**, I have this line inside my form (my\_module/src/Form/MyCustomForm.php).

```
$users = db_query('SELECT * FROM {users}');

```

`var_dump($users)` shows an object (of my query) and not the list of all users.

```
object(Drupal\Core\Database\Statement)[322] public 'dbh' => object(Drupal\Core\Database\Driver\mysql\Connection)[20] protected 'needsCleanup' => boolean false protected 'target' => string 'default' (length=7) protected 'key' => string 'default' (length=7) protected 'logger' => null protected 'transactionLayers' => array (size=0) empty protected 'driverClasses' => array (size=0) empty protected 'statementClass' => string 'Drupal\Core\Database\Statement' (length=30) protected 'transactionSupport' => boolean true protected 'transactionalDDLSupport' => boolean false protected 'temporaryNameIndex' => int 0 protected 'connection' => object(PDO)[15] protected 'connectionOptions' => array (size=10) 'database' => string 'theming' (length=7) 'username' => string 'root' (length=4) 'password' => string 'private' (length=8) 'prefix' => array (size=1) ... 'host' => string 'localhost' (length=9) 'port' => string '3306' (length=4) 'namespace' => string 'Drupal\Core\Database\Driver\mysql' (length=33) 'driver' => string 'mysql' (length=5) 'pdo' => array (size=4) ... 'init_commands' => array (size=1) ... protected 'schema' => null protected 'prefixes' => array (size=1) 'default' => string '' (length=0) protected 'prefixSearch' => array (size=2) 0 => string '{' (length=1) 1 => string '}' (length=1) protected 'prefixReplace' => array (size=2) 0 => string '' (length=0) 1 => string '' (length=0) public '_serviceId' => string 'database' (length=8) public 'allowRowCount' => boolean false public 'queryString' => string 'SELECT * FROM users' (length=19)

```

Why?

# Answer
> 7 votes
There's nothing different from 7.x with db\_query(), it returns a result set where you can fetch results from or loop over it. Refer to the database API documentation.

However, there are even less reasons for doing a direct database query in 8.x than in 7.x, and doing the query by hand is very likely going to be more complicated because of the data tables.

Use entity query instead:

```
<?php
$uids = \Drupal::entityQuery('user')
  ->execute();
?>

```

Executing an entity query always returns entity IDs which can then be loaded:

```
<?php
$users = \Drupal::entityManager()->getStorage('user')->loadMultiple($uids);
// Shorthand if you know that you have users:
$users = \Drupal\user\Entity\User::loadMultiple($uids);
?>

```

---
Tags: 8, database
---


title: Last modified using format_interval

text:
# Question
Title: Last modified using format_interval
I would like to show interval time for nodes were last modified. I am using the following code:

```
<?php print "Last Modified" . format_interval($node->changed, $langcode, "short"); ?>

```

I am using `$langcode` as proposed here to display it in Arabic, but it is not working and I am not sure if I am using it the right way because I get this error ***Notice: Undefined variable: langcode in include()***

Whenever I update any content; interval time still set to 0 sec, so what is wrong with the code?

# Answer
Your code contains two errors:

* You are using a variable which has not been initialized
* You are passing the wrong arguments to `format_interval()`

The required arguments are:

* `$interval`
It's not a timestamp, but the number of seconds until now. In your case, you should use `time() - $node->changed`.
* `$granularity` It's the number of units that are shown; if you pass 2 as value for `$granularity` and the interval is for 1 year, 3 months, and 2 weeks, `format_interval()` will return `"1 year 3 months"`.
* `$langcode`
It's the language code for the language to use. If you are hard-coding the language to be Arabic, you should use `"ar"`.
> 0 votes

---
Tags: nodes
---


# Question
Title: Can I change the default tab at /admin without losing access to /admin/tasks?
Below I have changed the default tab at `/admin` to `/admin/index`, but now `/admin/tasks` is 403. Even if I change `$items['admin/tasks']['access callback']` to `TRUE` I'm still denied access.

```
function hook_menu_alter(&$items) {
  $items['admin/tasks']['page callback'] = 'system_admin_menu_block_page';
  $items['admin/tasks']['access arguments'] = $items['admin']['access arguments'];
  $items['admin/tasks']['file'] = $items['admin']['file'];
  $items['admin/tasks']['type'] = MENU_LOCAL_TASK;

  $items['admin']['page callback'] = $items['admin/index']['page callback'];

  $items['admin/index']['type'] = MENU_DEFAULT_LOCAL_TASK;
  unset($items['admin/index']['page callback']);
  unset($items['admin/index']['access arguments']);
  unset($items['admin/index']['file']);
}

```

How can I both restore access to `/admin/tasks` and set the default tab to `/admin/index`?

Resolution: The admin module was the problem. It's enabled by default in my installation profile.

# Answer
This is cleaned up some and prevents the admin module from botching /admin/tasks.

```
/**
 * Implements hook_menu_alter().
 *
 * Change default tab at /admin to that of the index rather than tasks.
 */
function hook_menu_alter(&$items) {
  $items['admin/tasks']['page callback'] = 'system_admin_menu_block_page';
  $items['admin/tasks']['access arguments'] = $items['admin']['access arguments'];
  $items['admin/tasks']['file'] = $items['admin']['file'];
  $items['admin/tasks']['type'] = MENU_LOCAL_TASK;

  $items['admin']['page callback'] = $items['admin/index']['page callback'];

  $items['admin/index']['type'] = MENU_DEFAULT_LOCAL_TASK;
  unset($items['admin/index']['page callback']);

  unset($items['admin/index']['access arguments']);
  unset($items['admin/index']['file']);
  unset($items['admin']['menu_name']);
  // Prevent admin module from taking over in this case, but do not change
  // behavior.
  if (module_exists('admin')) {
    $items['admin/tasks']['access arguments'][] = NULL;
  }
}

```
> 0 votes

# Answer
please find this code to do this

```
function hook_menu_alter(&$items) {
$a_title = $items['admin']['title'];
$admin = $items['admin'];
$t_title = $items['admin/tasks']['title'];
$tasks = $items['admin/tasks'];
$i_title = $items['admin/index']['title'];
$index = $items['admin/index'];
$items['admin/tasks'] = $admin;
$items['admin/tasks']['title'] = $t_title;
$items['admin/tasks']['type'] = MENU_LOCAL_TASK;
$items['admin'] = $index;
$items['admin']['title'] = $a_title;
unset($items['admin']['type']);
unset($items['admin/index']);
$items['admin/index'] = $tasks;
$items['admin/index']['title'] = $i_title;
}

```
> 0 votes

---
Tags: routes
---


# Question
Title: Displaying a standard picture when user has not uploaded a picture
I am using the following code.

```
if ($logged_in) {
  $user = user_load($user->uid);
  print theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $user->picture->uri));
}

```

It displays the user's picture.

How should I modify it so that so that when the user has NOT uploaded or has deleted his picture a standard "no photo" picture is displayed instead as in:

```
$no_avi = "http://example.com/sites/default/files/nophoto.jpg";
echo("<img src=\"$no_avi\" />");

```

The User Picture Field module does not provide this capability.

# Answer
Basing on the code used by `template_preprocess_user_picture()`, I would suggest the following code.

```
if (!empty($user->picture)) {
  if (is_numeric($user->picture)) {
    $account->picture = file_load($user->picture);
  }
  if (!empty($user->picture->uri)) {
    $filepath = $user->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}
if (isset($filepath)) {
  $alt = t("@user's picture", array('@user' => format_username($account)));
  if (module_exists('image') && file_valid_uri($filepath)) {
    $user_picture = theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
  else {
    $user_picture = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
}

```

If you didn't need to use a specific style, but you could use the one set in Drupal settings, the code would simply be the following one.

```
$user_picture = theme('user_picture', array('account' => $user));

```

Keep in mind that there are some places where Drupal already shows the user's picture. If you just need to change the image style used for the user's picture, that is possible from Drupal settings (see this other answer). If you need to show the user's picture in a page where Drupal doesn't show them, I would set the default image style for the user's picture in Drupal's admin settings, and use the following code.

```
$user_picture = theme('user_picture', array('account' => $user));

```
> 2 votes

# Answer
Why would you want to upload programmatically, Drupal provide this functionality for default picture.

Go to `Configuration -> People -> Account Settings`.

Under personalisation section you can provide the url of the default picture and can select the image style to use for the picture.
> 1 votes

---
Tags: users
---


title: Buying userpoints?

text:
# Question
Title: Buying userpoints?
I am using Drupal Commerce, Userpoints, and Commerce Userpoints. How can I add the possibility for a user to buy some userpoints with different payment methods?

# Answer
> 4 votes
Create a product of type **userpoints** and upon successful payment add a **rule** to update userpoints for that user.

---
Tags: commerce, userpoints
---


title: How do I print the body of a node?

text:
# Question
Title: How do I print the body of a node?
I am struggling to work out how to print a node body on a page.

I normally use something like this `print $node->field_manufacturer[0]['view'];` but I am unsure how to print the body of a node.

How can I achieve it?

# Answer
> 3 votes
You can view the whole structure and content of a node by writing:

```
<pre><?php print_r($node); ?></pre>

```

And then choosing what deems appropriate.

To print the node body, you should use `$node->content['body']['#value']`.

# Answer
> 16 votes
For Drupal 7, a better style is to use field\_get\_items. E.g.:

```
<?php
  $body = field_get_items('node',$node, 'body');
  print $body[0]['value'];
?>

```

# Answer
> 14 votes
Just try this for Drupal 7

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

```

# Answer
> 10 votes
If `$node` is a node object obtained for example with `node_load()`, in Drupal 7 this is the structure of `$node->body`.

The language set for the node I used in the screenshot is English, and the input format is full HTML. As far as I can see, the content of the body is always contained in the "und" index, whatever language has been set for the node.

In Drupal 6, `$node->body` is a string.

If you implemented `hook_nodeapi('view')` (Drupal 6) or `hook_node_view()` (Drupal 7) the content of the body is found, respectively, with `$node->content['body']['#value']`, and `$node->content['body'][0]['#markup']`.

# Answer
> 3 votes
drupal 7 :

```
 <?php print $node->body['und'][0]['value'] ?>

```

# Answer
> 0 votes
The following usually works:

```
<?php print $node->body['value']; ?>

```

# Answer
> 0 votes
Perhaps a little late, but try the following, if you are using Drupal 6.

```
     <?php print $node->content['body']['#value'] ?>

```

---
Tags: nodes
---


# Question
Title: How to display field collection fields in tabs on add another item button?
I have a content type which has a multivalued field collection field. In this field I have a set of field collection items. In field collection I have put the fields in horizontal tabs.

But the problem is when I click on add another item button it adds those set fields in a new row not in another horizontal tab.

Is there any module which should add fields in new horizontal tab? Or any custom code hint?

# Answer
I have found the solution.

I used multiple value widget module. It does exactly the same.
> 0 votes

---
Tags: 7, entities
---


title: How to remove source from RSS feed?

text:
# Question
Title: How to remove source from RSS feed?
I have a site where Drupal generates rss through a view and then an external source uses that rss. Now the client says that I should remove the source from RSS. How can I remove the source from rss? See the source in image. The source shows the url.

# Answer
> 0 votes
You can make a custom template taking views-view-rss.tpl.php as starting point. See the template under modules and views/theme/views-view-rss.tpl.php

---
Tags: views, feeds
---


# Question
Title: Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page
Ryan has some great code that you can programmatically create an order

```
<?php
global $user;
$product_id = 1;
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid, 'checkout_checkout');

// Save the order to get its ID.
commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);
?>

```

http://www.drupalcommerce.org/questions/3259/it-possible-drupal-commerce-work-without-cart-module

I have a site where I want to take anonymous donations so I have two problems.

1. If a user is not logged into the site they get an access denied message
2. The checkout process asks for name, address etc.

What I want to do is have a page where you confirm the amount then get taken to the payment page. In this case I am using PayPal WPS so redirecting there would be great.

Any advice you could give would be appreciated.

# Answer
**1. If a user is not logged into the site they get an access denied message**

***I got something working but I highly doubt it is best practice.***

In the end I cheated. On my form where you put your details including email address I create a user account on the fly and then log the user in. If an email address is all ready in use I log the user in. (I make sure you are not using the admin email address).

As my site only has the donation form page when you hit that page it makes sure you are logged out (if you are not admin). On a successful transaction it logs you out. I have turned off order history / put redirects in place so you can only go on the pages I know about when logged in. No personal details are stored and can't see past donations

***In my situation I am happy with how this works. It is not ideal and will only work in a few cases.***

**2. The checkout process asks for name, address etc.**

I went to

*/admin/commerce/config/checkout*

And disabled

* Account information
* Billing information
> 0 votes

# Answer
You may try to test a new module called Commerce Drush which has the following syntax:

```
drush commerce-order-add 1
drush --user=admin commerce-order-add MY_SKU123

```

---

**Manual solution**

For creating an order programatically in Commerce, you can use the following code (it works with drush as well, e.g. `drush -vd -u "$1" scr order_code-7.php`). Please note that `commerce_payment_example` module is required.

```
<?php

  if (!function_exists('drush_print')) {
    function drush_print ($text) {
      print $text . "\n";
    }
  }

  $is_cli = php_sapi_name() === 'cli';

  global $user;

  // Add the product to the cart
  $product_id = 5;
  $quantity = 1;

  if ($is_cli) {
    drush_print('Creating new order for ' . $quantity . ' item(s) of product ' . $product_id . '...');
  }

  // Create the new order in checkout; you might also check first to
  // see if your user already has an order to use instead of a new one.
  $order = commerce_order_new($user->uid, 'checkout_checkout');

  // Save the order to get its ID.
  commerce_order_save($order);

  if ($is_cli) {
    drush_print('Order created. Commerce order id is now ' . $order->order_id);
    drush_print('Searching product ' . $product_id . ' in a Commerce system...');
  }

  // Load whatever product represents the item the customer will be
  // paying for and create a line item for it.
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    if ($is_cli) {
      drush_print('  Cannot match given product id with a Commerce product id.');
    }

    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  if ($is_cli) {
    drush_print('  Found a Commerce product ' . $product->product_id . '.');
  }

  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

  if ($is_cli) {
    drush_print('  Added product to the cart.');
  }

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  if ($is_cli) {
    drush_print('Saving order...');
  }

  // Save the order again to update its line item reference field.
  commerce_order_save($order);

  // Redirect to the order's checkout form. Obviously, if this were a
  // form submit handler, you'd just set $form_state['redirect'].

  if ($is_cli) {
    drush_print('Checking out the order...');
  }

  commerce_checkout_complete($order);

  if ($is_cli) {
    drush_print('Marking order as fully paid...');
  }

  $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

  if (!$payment_method) {
    if ($is_cli) {
      drush_print("  No example payment method found, we can't mark order as fully paid. Please enable commerce_payment_example module to use this feature.");
    }
  }
  else {
    if ($is_cli) {
      drush_print("  Creating example transaction...");
    }

    // Creating new transaction via commerce_payment_example module.
    $charge      = $order->commerce_order_total['und'][0];

    $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $charge['amount'];
    $transaction->currency_code = $charge['currency_code'];
    $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $transaction->message = 'Name: @name';
    $transaction->message_variables = array('@name' => 'Example payment');

    if ($is_cli) {
      drush_print("  Notifying Commerce about new transaction...");
    }

    commerce_payment_transaction_save($transaction);

    commerce_payment_commerce_payment_transaction_insert($transaction);
  }

  if ($is_cli) {
    drush_print("Marking order as completed...");
  }

  commerce_order_status_update($order, 'completed');

  if ($is_cli) {
    drush_print("\nDone.");
  }

```

---

Note: As suggested in the comment, if you got error about payment method is *unknown* while saving the order, make sure you've specified it, e.g.

```
$order->data['payment_method'] = 'commerce_payment_example|commerce_payment_commerce_payment_example';
commerce_order_save($order);

```
> 12 votes

# Answer
This modified script works also for the anonymous users:

```
<?php
global $user;

$product_id = 2;
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid, 'checkout_checkout');
// Save the order to get its ID.
commerce_order_save($order);

// Link anonymous user session to the cart
if (!$user->uid) {
    commerce_cart_order_session_save($order->order_id);
}

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);

```
> 5 votes

# Answer
You need to add commerce\_cart\_order\_session\_save() so anonymous user have their session to link the browser with cart content.
> 1 votes

---
Tags: 7, commerce
---


title: Omega Tools Transform Theme Name error

text:
# Question
Title: Omega Tools Transform Theme Name error
I am getting the following error when trying to create an omega-sub-theme on my local machine (OSX) using drush on Acquia Dev Desktop.

```
PHP Fatal error:  Call to undefined function _omega_tools_transform_theme_name()

```

Install process I followed goes:

1. Set Name
2. unique machine name
3. Omega (HTML5 base)
4. Default Starterkit
5. Destination: sites/all/themes
6. keep starterkit read me files
7. enable theme/ set as default
8. download libraries defined in libraries.make

Fatal error occurs here.

# Answer
> 0 votes
As per Clive's comment the error was Omega-Tools. I had disabled it but it required uninstalling and then I even had to delete the module from the modules directory to stop it from showing up in the modules page. After this I encountered this issue ( https://www.drupal.org/node/2200473 ) and then everything worked. Thanks Clive.

---
Tags: drush, theming, acquia-dev-desktop
---


title: How do I override bootstrap.js?

text:
# Question
Title: How do I override bootstrap.js?
I'm using a Bootstrap 3 child theme in Drupal 7. All is working well, except I can't seem to be able to override bootstrap.js at sites/all/themes/bootstrap/js/bootstrap.js in my own theme.

Am I missing something?

# Answer
> 0 votes
It is probably using a CDN, as per https://drupal.org/node/1978010.

> Bootstrap Methods
> There are currently two types of supported methods for adding Bootstrap into your sub-theme. By default, the Bootstrap base theme enables a CDN to provide the necessary files.
> If this method suits you then you can skip this step.

# Answer
> 0 votes
Inside template.php of your theme:

```
/**
* Implements hook_js_alter().
*/
function client_js_alter(&$js) {
    // Path to your theme
    $theme_path = drupal_get_path('theme', 'client');
    // Your overwrites
    $bootstrap_fix = $theme_path . '/js/bootstrap_fix.js';
    $js[$bootstrap_fix] = drupal_js_defaults($bootstrap_fix);
    $js[$bootstrap_fix]['group'] = JS_THEME;
    $js[$bootstrap_fix]['scope'] = 'footer';
    $js[$bootstrap_fix]['weight'] = 2;
}

```

---
Tags: 7, theming
---


# Question
Title: Drush rsync command failed: No such file or directory
I am new to use Drush.

this following is my .drushrc.php file

```
$aliases['server'] = array (
  'remote-host' => '162.243.78.240',
  'remote-user' => 'root',
);
$aliases["dxb"] = array (
  '#name' => 'dxb',
  'root' => '/var/www/dev/daxuebao',
);

```

I try to use this following command to sync local site to remote site

```
$ drush rsync @self @dxb

```

But it alert me:

```
rsync: mkdir "/var/www/dev/daxuebao" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at /SourceCache/rsync/rsync-42/rsync/main.c(544) [receiver=2.6.9]
rsync: connection unexpectedly closed (8 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at /SourceCache/rsync/rsync-42/rsync/io.c(452) [sender=2.6.9]
Could not rsync from /Users/tangmonk/Sites/drupal/daxuebao// to      [error]
/var/www/dev/daxuebao/

```

It seems directory `/var/www/dev/daxuebao` do not exist, so I try to mkdir to my server :

```
$ mkdir /var/www/dev/daxuebao

```

The I type `$ drush rsync @self @dxb` again, But still above problem.
How to solved it?

# Answer
Make sure the string containing the directory does not have extra blank spaces at the end. Trim it if possible. I was getting a similar message when I was using the option `--files-from=myDirList` and I have some spaces after the directory name inside the myDirList.
> -1 votes

---
Tags: drush
---


# Question
Title: How can I call node id in template file?
Using Drupal 7.

I have a `page--front.tpl.php` template file. And I want import a node in this file.

How can I do it?

# Answer
Here is my solution:

```
<?php
$view_mode = 'teaser'; // Or 'full' for example

$node = node_load(2);

$view = node_view($node, $view_mode);

print render($view);
?>

```
> 0 votes

---
Tags: nodes, 7
---


title: Webserver authentication

text:
# Question
Title: Webserver authentication
I was looking a module that implements single sign on for MS Windows networks. I found Webserver Authentication (https://www.drupal.org/project/webserver\_auth). But I activated the module before configure it and now I can't access as ADMIN, or as any other developer user to keep working on the configuration of my project.

Does anyone had this problem before and can guide me to deactivate or uninstall that module??

# Answer
Drush may be the best option. You have a command to uninstall a module : drush pm-uninstall module-name

Otherwise there is a really tricky and dangerous way to do it : Go on your database on the "system" table. And search for the line with your module and set the status to 0. After that you may need to clear your cache with the function : drupal\_flush\_all\_caches() (add it to a index.php and remove it after).

The second method is tricky and you should prefer the one with drush. I just explain it if you don't manage to install drush on windows.
> 1 votes

---
Tags: 7
---


title: Clean URL's not respected on local

text:
# Question
Title: Clean URL's not respected on local
I have set up my Apache 2.4 on this new Yosemite machine to use vhosts but the clean urls are yielding 404s. The .htaccess works on the 1and1 server and I'm using it in this folder. Reading other SO posts say to enable mod-rewrite and AllowOverride All which I believe I have done. Here is my vhost configuration

This is my working .htaccess that production uses: For more clarity this is the output of apachectl -M

```
Loaded Modules:
 core_module (static)
 so_module (static)
 http_module (static)
 mpm_prefork_module (static)
 authn_file_module (shared)
 authn_core_module (shared)
 authz_host_module (shared)
 authz_groupfile_module (shared)
 authz_user_module (shared)
 authz_core_module (shared)
 access_compat_module (shared)
 auth_basic_module (shared)
 reqtimeout_module (shared)
 filter_module (shared)
 mime_module (shared)
 log_config_module (shared)
 env_module (shared)
 headers_module (shared)
 setenvif_module (shared)
 version_module (shared)
 proxy_module (shared)
 proxy_connect_module (shared)
 proxy_ftp_module (shared)
 proxy_http_module (shared)
 proxy_fcgi_module (shared)
 proxy_scgi_module (shared)
 proxy_wstunnel_module (shared)
 proxy_ajp_module (shared)
 proxy_balancer_module (shared)
 proxy_express_module (shared)
 slotmem_shm_module (shared)
 lbmethod_byrequests_module (shared)
 lbmethod_bytraffic_module (shared)
 lbmethod_bybusyness_module (shared)
 unixd_module (shared)
 status_module (shared)
 autoindex_module (shared)
 vhost_alias_module (shared)
 negotiation_module (shared)
 dir_module (shared)
 alias_module (shared)
 rewrite_module (shared)
 php5_module (shared)

```

I have moved the application folder into OS X webserver and commented out the vhost include statement to ensure that if there is an issue with my vhost it should show up. However, there is a 404 response when drilling down to /user.

What am I overlooking? thx, sam

# Answer
It may be that your Apache vhost and/or .htaccess need updating.

Yosemite uses Apache 2.4, which replaces some access control statements used in 2.2 and prior.

'Allow from all' becomes 'Require all granted'

'Deny from all' becomes 'Require all denied'

See htaccess protections do not work on Apache 2.4 without mod\_access\_compat for the ongoing Drupal 7 core discussion. Upgrading to 2.4 from 2.2 gives some guidance on upgrading configurations.
> 3 votes

---
Tags: .htaccess
---