# Question
Title: How drupal keeps revisions for some content types only
In Drupal 6 for some content types when editing a node its replicated and keeps revisions for that content type by keeping vid (version id) for that in the table, But for some other content types it wont make new table entries when editing that content types . How is it like that ? Or is there any criteria to keep revisions for some content type only ?

**update from comment**

The revision information can be done when creating a content type item itself , but how come its auto selected for some content types ?

**2nd update**

When creating a new content type i can see the options as follows :

But as you can see , `revision settings is inside submission form settings` but `**its disabled**` here , how i can set revisions for particular content type only for some content type only .

# Answer
> 1 votes
**For D7:**

**admin/structure/types/manage/YOUR\_CONTENT\_TYPE**

You need to tick the checkbox `"Create new revision"` for saving revisions of any content type you want.

**For D6:**

**administer/content management/content types/edit/workflow**

Thanks!

---
Tags: nodes, 6
---


# Question
Title: Theme not working when using non-standard port number
I've been having some performance issues with my local **WAMP** install and saw a suggestion to move Apache to a different port. I achieved this by updating `httpd.conf`:

```
Listen 89
ServerName localhost:89

```

I also update my **vhosts** to use the new port:

```
<VirtualHost *:89>
    ServerName mysite.local
    DocumentRoot "D:\wamp\www\mysite"
</VirtualHost>

```

This works. I can now access the site via `mysite.local:89`. However, the site appears unstyled because the CSS and JS files are not linked properly. For example, the following CSS file cannot be found:

```
<link type="text/css" rel="stylesheet" href="http://mysite.local/sites/default/files/css/css_0-h4tIT-Kdty3gonMCX41fM-7MgTrV9BMd5XQoTqeaQ.css" media="all">

```

I need the CSS and JS to use `mysite.local:89` instead of `mysite.local`. When I change this manually via the web inspector it works.

How can I change the CSS and JS imports to use the new port?

**Update on WAMP Slowness**

For anyone who is interested, WAMP is running much better now. I followed the recommendations in the following article (specifically, I disabled IPv6, put all host file entries on one line, moved Apache to a new port): http://devside.net/wamp-server/wamp-is-running-very-slow

# Answer
It should just be a matter of setting the `$base_url` in settings.php

> 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.

For your case that would be:

```
$base_url = 'http://mysite.local:89';

```
> 3 votes

---
Tags: theming
---


# Question
Title: Configuration management sync vs active vs staging
The documentation on config management talks about a `CONFIG_SYNC_DIRECTORY` setting, but then there is also mention of `CONFIG_ACTIVE_DIRECTORY` and `CONFIG_STAGING_DIRECTORY` setting throughout comments both on d.o and in stack overflow.

What are these two different setups about?

# Answer
This has changed, before Drupal beta 14 it was active/staging now it is sync. These are the settings in settings.php:

```
Drupal 8 beta 14:
$config_directories['active'] = 'sites/default/files/config_HASH/active';
$config_directories['staging'] = 'sites/default/files/config_HASH/staging';

Drupal 8 rc1:
$config_directories['sync'] = 'sites/default/files/config_HASH/sync';

```
> 7 votes

# Answer
Timely question. This is being discussed at Update documentation that mentions active CMI directory. active was removed. Reviewing the documentation in the patch should clarify everything.

Long story short: staging has been replaced by sync and active is no longer created by default.
> 5 votes

---
Tags: 8, configuration
---


title: Alter hook_field_formatter_view?

text:
# Question
Title: Alter hook_field_formatter_view?
What is the best way to alter field output? I found "hook\_field\_formatter\_view" but seems nothing like "hook\_field\_formatter\_view\_alter" exists. In my case I have address fields (Addressfield module) which used in "Shipping" and "Billing" panes on DrupalCommerce's checkout page. I want to add some js to these fields, preferable using Drupal's Form API "#attached"

# Answer
You may want to try to alter it with a preprocess function:

```
function example_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if ($field_name == 'field_example_field') {
    // Your code here.
  }
}

```

I ran a test to modify *$variables\['element'\]\['#attached'\]\['js'\]* but Drupal didn't recognize the changes to the element. Not sure why. So, you may have to use drupal\_add\_js.
> 9 votes

# Answer
The `hook_field_formatter_view()` specified by the display configuration is called in `field_default_view()`, which is itself called (a layer or two below it) by `field_attach_view()`.

You can see from the second link that this calls `hook_field_attach_view_alter()` after it's finished with the field formatters:

```
drupal_alter('field_attach_view', $output, $context);

```

so you should be able to define that hook.

Note, though, that you'll have to re-find the field on the entity, as it runs the hook for the entire render array, not simply the render array for one field. But the example hook linked to above gives an example of how to do that.
> 5 votes

---
Tags: entities
---


# Question
Title: How can I programmatically alter Webform "To Email Address"?
I want to change email addresses based on postal codes entered by users. My code looks like below.

```
function my_webform_tracker_webform_submission_render_alter(&$renderable) {
  $node_id = (int)$renderable['#node']->nid;
  if ($node_id == 257) {
    $postal_code = (int)$renderable['#submission']->data[5][0];
    if($postal_code >= 14000 && $postal_code <= 14990) {
      $renderable['#email'][email] = "thisemailid@mydomain.com";
      $renderable['#node']->webform['emails'][1]['email'] = "thisemailid@mydomain.com";
      $renderable['#node']->webform['emails'][2]['email'] = "thisemailid@mydomain.com";
      //print "<pre>"; print_r($renderable); exit;
    }
  }
}

```

I tried a lot but the email id seems to be not changed. Please help me figure this out.

# Answer
> 1 votes
I think a more apt place to alter the destination email would be `hook_mail_alter()` where Drupal lets you alter an email before sending it out. The webform module includes all the submission data in the `$message['params']['submission']` object.

You can do something like this in your module:

```
/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {

  //Catch Webform submissions when we have a valid postal code
  if($message['id'] == 'webform_submission') {
    $postal_code_component = 5;
    if(isset($message['params']['submission']->data[$postal_code_component][0])) {
      $postal_code = (int) $message['params']['submission']->data[$postal_code_component][0];

      //Find right addressee to switch to
      if(0 <= $postal_code && $postal_code <= 13999 ) {
        $message['to'] = 'addressee.1@example.com';
      } elseif(14000 <= $postal_code && $postal_code <= 14990) { //Etc...
        $message['to'] = 'addressee.2@example.com';
      } else { //Catchall
        $message['to'] = 'addressee.3@example.com';
      }
    }
  }
}

```

# Answer
> 0 votes
I figured it out, actually I was using wrong hook to do the task. The right on would be "hook\_webform\_submission\_presave". So my code will look like,

```
    function my_webform_tracker_webform_submission_presave($node, &$submission) {
      $postal_code = (int)$renderable['#submission']->data[5][0];
      if($postal_code >= 14000 && $postal_code <= 14990) {
        $node->webform['emails'][1]['email'] = "thisemailid@mydomain.com";
        $node->webform['emails'][2]['email'] = "thisemailid@mydomain.com";
      }
    }

```

Thank You everyone for help!!

---
Tags: 7, webforms
---


# Question
Title: Image upload in a node gives required error
we have a node to which we upload many pictures. This time, after ~ 337 pictures all of the following pictures are marked as failure with an error but as message is just given "**Field Bilder is required**". Bilder (translates to images) is the field we already uploaded 300+ images.

In the recent Drupal log is no message concerning upload errors. Any clues what could cause this problem?

# Answer
Most probably the upload is limited due to **php settings**. There is not only a setting for max upload per file, but also a max for a post.

On this page you can find how to solve in this link

If this doesn't work, there might be a setting for `max_execution_time` in `php.ini`, which cuts off the upload script if it takes too long.
> 0 votes

---
Tags: nodes, media
---


# Question
Title: View node public OR only to verified/role by choice user
It's possible to set the **permission** to view for a Content type. But how can i let the choice to view to public OR only verified users/role to the user?

Making 2 different **Content types** would be an easy solution, but is not convenient. Also, **Node Access** is to difficult for users (too many choices). Need just a button or check box to hide or view the node public. If it's hidden for public, it should be visible to registered users.

# Answer
> 0 votes
Found a way to do this with tags. Feel free to add information about doing this with tags:

* Added a taxonomy 'visibility' with 2 tags: *public* and *closed*.
* Added to Contenttype a field with a *selection-list* (so, a user can only choose one).
    + (set it to *requiered* to only have 2 options.)
    + (in my case, i set the *default* to public.)
* Enabled taxonomy-module '*Taxonomy Access Control*'
* go to admin/config/people/taxonomy\_access \>\> anonymous \>\> choose \[edit access rule\]
    + (in my case it's admin/config/people/taxonomy\_access/role/1/edit)
* Under New \>\> choose the term 'closed' (or your equivalent like 'not for mother-in-law ;-) ).
* Set everything to D (Deny)
* When Content Access is also on, set grant priority to -1 on the contenttype-page (admin/structure/types/manage/\[contenttype\]/access

---
Tags: users
---


# Question
Title: Omega theme conflicts with CSS of Seven administration theme, how to resolve?
Not sure exactly where my problem stems from but here goes: I am developing a site with an **Omega4 subtheme**. Something in the css rules is conflicting with the CSS for the Div: `Views-ajax-popup` and overwriting the default white back ground to none. This makes the UI visually hard to use, and while I can get by with highlighting the text, but my other site users are not so adept.

The issue is I have no idea what's causing the conflict, or where to address it. In **chrome inspector**, setting the background to white corrects what I want. The css for the body seems to be the issue, it's getting it's styles Media=screen, and I can see that the default CSS is white, but it being overwritten but again no idea from where.

So, what's causing my css conflict with the admin theme and how do I fix it?

# Answer
When Drupal loads the Seven theme for admin, it doesn't load files from any other theme. Same goes vice-versa. So it's unlikely either theme can be to blame, or even involved.

There's no way to guess from here what styles are overwriting others unfortunately, you'll just need to dig further with dev tools until you find the culprit.

Methodically disabling contrib/custom modules and testing the results each time is a good idea if you can't see any where else to look in the dev tools, you can find or at least rule out a culprit that way.

You could also search the files for those modules for instances of "views-ajax-popup", maybe something you have installed is specifically targeting it through CSS or javascript.
> 1 votes

---
Tags: theming
---


title: Override tpl for custom menu page

text:
# Question
Title: Override tpl for custom menu page
I have created a custom menu with hook menu `booking/%/reschedule` and where % is nid of bookings ( content type ), I want to override tpl file for this page in my theme. I tried with `page--booking--%--reschedule.tpl.php` but its not working.

# Answer
> 2 votes
Write this function in your `template.php` file, which is located in your theme (untested):

```
function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'booking' && $alias_parts[2] == 'reschedule') {
    $vars['theme_hook_suggestions'][] = 'page__bookingtemplate';
  }
}

```

Then you can create a new template file which is called `page--bookingtemplate.tpl.php` and after clearing the cache, it should work.

Credits to Clive for this post.

# Answer
> 0 votes
You can create a menu by adding code in your file

```
<?php
function THEMENAME_links__system_MENUNAME_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l($link['title'], $link['href'], $link);
  }
  return $output;
}
?>

```

---
Tags: theming, routes
---


title: Hook_menu_alter not working?

text:
# Question
Title: Hook_menu_alter not working?
```
**
* Implements hook_menu().
*/

define('RATE_PATH_RESULTS_PAGE', 'node/%node/rating');

function rate_menu() {
  $menu = array();

   $menu[RATE_PATH_RESULTS_PAGE] = array(
     'title' => 'Voting results',
     'page callback' => 'rate_results_page',
     'page arguments' => array(1),
     'access callback' => 'rate_results_page_access',
     'access arguments' => array('view rate results page', 1),
     'type' => MENU_LOCAL_TASK,
     'weight' => 10,
    'file' => 'rate.results.inc',
);

  return $menu;
}

```

Above menu item comes from rate module, I want to override permission of this menu item. For now permissions are defined for user roles from permissions page. But according to my requirement I want this menu link visible to users on nodes only when user is author of node. Due to this I want to take control of this menu item in my custom module.

```
function custom_menu_alter(&$menu){
  $menu[RATE_PATH_RESULTS_PAGE] = array(
    'title' => 'Voting results page',
 );

}

```

I am trying by writing above function for alter menu in my custom module. Please guid me with proper way, what I am doing wrong.

Thanks!

# Answer
> 3 votes
You're overwriting the whole item with this:

```
$menu[RATE_PATH_RESULTS_PAGE] = array(
  'title' => 'Voting results page',
);

```

Which clears out the page callback, access callback, and so on.

Instead, you want to replace the individual relevant components like this:

```
$menu[RATE_PATH_RESULTS_PAGE]['title'] = 'Voting results page';

```

---
Tags: hooks, routes
---


# Question
Title: How to send mail from drupal 7 efficently and avoid 'Too many concurrent SMTP connections' error?
I'm using the smtp module to send mail from a drupal 7 installation throught gmail. In

```
 /admin/config/system/smtp

```

I set

```
 smtp server 'smtp.gmail.com'
 smtp port '587'
 use encryption 'use tls'

```

and i set my valid mail 'something@gmail.com'.

Now, it's working, but some days ago a lot of mail, on the account something@gmail.com, began to arrive containing an error message:

```
 Delivery to the following recipient has been delayed:
 someBadGuy@somemail.com
 Message will be retried for 2 more day(s)
 Technical details of temporary failure:
 The recipient server did not accept our requests to connect. Learn more at https://support.google.com/mail/answer/7720
 [(10) somemail.com. [someip]:25: 421 Too many concurrent SMTP connections; please try again later. ]

```

There *were* and there *will always be* on my drupal site people registering with fake unreachable mail, so assuming i can't solve this problem, what this message means? It began some days ago, out of the blue, so i think something is changed, but i do not know precisely what. And do not know precisely **where**. (gmail, my provider, my server...)

Anyway, what is the best way to send mail from drupal, excluding the idea of setting up my own mail server and excluding gmail, as it implies this problem?

# Answer
> 1 votes
Logically speaking I'd say you have a few options:

1. Implement a mechanism to either stop fake users from signing up altogether, or to clear out the accounts in the time between them registering and the SMTP module doing its thing.
2. Hook into `drupal_mail` and implement some logic to stop emails being sent to addresses you determine are 'bad'
3. Convince Google to relax their parameters so you can send more mail (unlikely)
4. Use a service other than GMail which allows more capacity.

The error message suggests you're looking at resource limits here, so the only fix is to either get your provider to increase that limit for you, or stop as many emails being sent from your site in the first place.

# Answer
> 1 votes
Have you tried using the Mandrill module? https://www.drupal.org/project/mandrill

---
Tags: 7, emails
---


# Question
Title: Children of children not appearing in book navigation menu
UPDATE: I should mention that this is concerning the Book Navigation Block

---

I'm using the book module to display children of a book in a side menu. It displays the title of the book and it's children just fine. However the children of the children don't appear even after clicking on the parent page.

I searched in the module settings for book navigation however I can't seem to find a way to display them.

Is there anything that could possibly affect what sub items are displayed in a book?

# Answer
> 0 votes
book\_children(), which is used in the preprocessor for the "book\_nagivation" theme hook (template\_preprocess\_book\_navigation()) only retrieves the immediate children of the current book item, so you wouldn't expect the default "Book navigation" block provided by the Book module to show all children of the current book item recursively.

If you wanted to modify the behavior of this block in your theme, you could clone the template\_preprocess\_book\_navigation() from book.module, placing the function in the template.php file for your theme and renaming it to yourthemename\_preprocess\_book\_navigation(), and then create and call a modified clone of book\_children() that recursively collected all links in the book beneath the passed link.

If the behavior you wanted was to display the standard tree for all interior book pages, but display book's entire outline *only* when you are viewing main page of the book, you could alter your yourthemename\_preprocess\_book\_navigation() function so that it only calls the "get recursive tree" function when the $book\_link doesn't have a parent ($book\_link\['plid'\] == 0), and call book\_children() for all other cases.

# Answer
> 0 votes
This snippet has a level-variable. In the comments something is said about Drupal 7. Maybe you can do something with it. https://www.drupal.org/node/44648

---
Tags: 7, nodes
---


title: How to process url from user input?

text:
# Question
Title: How to process url from user input?
I am creating **LinkedImage** field, formatter and widget so that images can be linked to somewhere.

And I have an issue with the input. The user can set internal or external links like `/node/1`, `<front>` or `http://www.google.com`. But the `Url` object that is required for link render element has no method that would work with all of these.

The `Url::fromUserInput` will work with internal paths but not with `<front>`. The `Url::fromUri()` will work with `http://www.google.com` but not with `<front>` or `/node/1`.

So I had to implement logic to distinguish the format and also I had to add validation handler into the widget telling the user that the link has to start with forward slash or with http prefix.

But I do not like this approach. Seems like this is not how it is supposed to be done.

So how can I properly construct `Url` object from these three types of input?

Also another issue here is that if "malformed" URL is already set (ie. it hasn't been validated via my UI validation handler) then I will get WSOD and that is just really bad UX.

Plus, as you can see, `<front>` is not working with any of these methods whic hrequires additional logic.

# Answer
> 1 votes
I had the same problem, so please try this:

```
$url_object = \Drupal::service('path.validator')->getUrlIfValid($path);
$url_object->setAbsolute();
$url = $url_object->toString();

```

---
Tags: uri, 8
---


title: Views, Panels, Block not translating

text:
# Question
Title: Views, Panels, Block not translating
In a panel, I'm trying to add a view block and I'm trying to translate my views title l but it's not displaying anything or translating. Below you can see my settings in my panels.

If I dont override the title, it's still blank. I dont see the English or the FR translations.

# Answer
> 1 votes
I thought there was already support for translatable pane titles in Panels with the i18n\_panels submodule. However, looking at Issue #117934 which is currently marked fixed, there are still people providing patches. Though that issue title states it is for translatable Panel PAGE titles, the patch on comment #106 actually modifies code to make pane titles translatable.

Note that from an architectural perspective the approach in comment #106 is frowned upon because you are not supposed to pass dynamic text through t(). I would consider this a small permissible hack to get you across the finish line without wasting too much time.

---
Tags: views, blocks, panels, i18n-l10n
---


title: Menu Callback and CSRF

text:
# Question
Title: Menu Callback and CSRF
How can I get a link with the correct csrf token for an internal path? Here is what I have:

in mymodule.routing.yml

```
mymodule.test:
  path: '/mymodule-test'
  defaults:
    _content: 'Drupal\mymodule\TestController::handleTest'
    _title: 'Handles test'
  requirements:
    _permission: 'access content'
    _csrf_token: 'TRUE'

```

building the link:

```
//$url = Url::fromRoute('mymodule.test');
//$settings['url'] = $url->toString();
$settings['url']=Drupal::url('mymodule.test');

```

the url contains the token in the query string as I expect, but it doesn't validate if I try to visit the link. When I edit `CsrfTokenGenerator` and dump out the token and the expected token, they do not match. All I can come up with is that the token is being generated for the page that I'm currently viewing rather than the route that I'm generating the url for.

Am I missing something? any ideas are appreciated!

# Answer
> 4 votes
Routes that need CSRF tokens have the `_csrf_token: 'TRUE'` route option. That's how URLs pointing to those routes automatically get a CSRF token.

So we need to look at `\Drupal\Core\Access\RouteProcessorCsrf`:

```
public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
  if ($route->hasRequirement('_csrf_token')) {
    …
    if (!$bubbleable_metadata) {
      $parameters['token'] = $this->csrfToken->get($path);
    }
    else {
      // Generate a placeholder and a render array to replace it.
      $placeholder = hash('sha1', $path);
      $placeholder_render_array = [
        '#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
      ];

      // Instead of setting an actual CSRF token as the query string, we set
      // the placeholder, which will be replaced at the very last moment. This
      // ensures links with CSRF tokens don't break cacheability.
      $parameters['token'] = $placeholder;
      $bubbleable_metadata->addAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]);
    }
  }
}

```

So there we can see that if `$bubbleable_metadata` is `NULL`, then we generate the CSRF token right away. `$bubbleable_metadata` being `NULL` signals to the CSRF route processor that the URL is being generated in a context where no cacheability metadata and attachments can be bubbled (e.g. when generating a URL to be sent in an e-mail). The downside is that the HTML containing this URL will then be uncacheable (well, very poorly cacheable), because the CSRF token is depends on the session.

That's why in the other case, where `$bubbleable_metadata` is a `BubbleableMetadata` instance, that signals to the CSRF route processor that the URL is being generated in a context where cacheability metadata and attachments *can* be bubbled (e.g. when generating a URL to be rendered in some HTML). So there we generate a *placeholder token* that will be replaced with the *CSRF token*, and specify a "placeholder" attachment that will ensure that placeholder token is replaced with a CSRF token at the last possible moment. Consequently, the HTML that this URL ends up in is still perfectly cacheable, because the URL is cacheable.

Now that problem has been confirmed. If this happens in a preprocess function, as the following one, then you end up with `$variables['url'] = GeneratedUrl(…)`. Twig ought to bubble the cacheability metadata and attachment metadata in that object, but it does NOT, in all versions of Drupal 8 before 8.1.2. We're fixing this for Drupal 8.1.2 at https://www.drupal.org/node/2575519.

```
function hook_preprocess_HOOK(&$variables) {
  $variables['url'] = \Drupal::url('mymodule.test');
}

```

# Answer
> 2 votes
This is probably the same problem as token but that was recently fixed: Browse available tokens not shown

The problem is that your token isn't actually a token, it's just a placeholder for a token that will be replaced later. However, the action to do that replacement (called lazy builder) is not being attached/bubbled up properly.

Where are you calling this? Try a solution similar to what's in the issue if you have a link, or try to get the cacheability metadata from the return value of toString(TRUE) and attach that to some render array:

```
$url =  Url::fromRoute('mymodule.test')->toString(TRUE);
BubbleableMetadata::createFromRenderArray($element)
  ->merge($url)
  ->applyTo($element);

$variables['url'] = $url->getGeneratedUrl();

```

As far as I understand, this is supposed to just work, but it apparently doesn't under some conditions. We'll need to see if we can fix that in core.

# Answer
> 0 votes
Finally came up with a solution.

```
$urlBubbleable = $urlObject->toString(TRUE);
$urlRender = array(
  '#markup' => $urlBubbleable->getGeneratedUrl(),
);
BubbleableMetadata::createFromRenderArray($urlRender)
  ->merge($urlBubbleable)->applyTo($urlRender);
$url = \Drupal::service('renderer')->renderPlain($urlRender);

```

It's my opinion that there should be a much easier way to accomplish this. We should be able to process the URL without having to pass it through the renderer.

But, for now, this works.

---
Tags: 8, routes, csrf
---


title: how to see node revision user in a view

text:
# Question
Title: how to see node revision user in a view
In drupal 7, I have revisions turned on, and I want to make a view to display the last updated date and the user who last updated it. The problem is I cannot get a field for "revision user" as an available field to see . The only revision fields available are the updated date, and log message.

# Answer
Please create view (content revisions view) like below images:

In view relationships please add  `content revisions : user`  for user information

Thanks!
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Which version of Behat (Guzzle) would be okay to use on a RHEL server with PHP 5.4?
On a Red Hat Enterprise Linux Server release 7.1 (Maipo) development server using \[Behat Drupal Extension\]\[1\], a RHEL 7 / PHP 5.4 installation. When I try to run behat from the command line on a dev server, I get the following error:

```
$ ./vendor/bin/behat

```

> Feature: First Playing with features and exploring
>
> `@api`
>
> `Scenario: Run cron # features/first.feature:6
>  PHP Fatal error: Call to undefined function GuzzleHttp\Handler\curl_reset()`
>
> in /var/www/html/sites/default/behat-tests/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 78

From answers below, it appears the the version of Guzzle bundled with this requires 5.5 or greater.

```
  guzzlehttp/guzzle               6.1.0   Guzzle is a PHP HTTP client library
  guzzlehttp/promises             1.0.3   Guzzle promises library
  guzzlehttp/psr7                 1.2.0   PSR-7 message implementation

```

**My question:** what version of Guzzle should I use in order to be able to run test on a server with PHP 5.4?

# Answer
> Call to undefined function GuzzleHttp\Handler\curl\_reset()

Means PHP is trying to find the function `curl_reset()` in the namespace `GuzzleHttp\Handler`.

It does that because it can't find it in the global namespace (where it should be). `curl_reset()` was only introduced in PHP 5.5, and you have version 5.4, so your version just isn't compatible with Guzzle 5.

Guzzle isn't explicitly listed as a dependency in the Behat extension's composer.json file, so one of the other libraries must depend on it. I'm not sure it would even be worth the time trying to unpick that, upgrading php would be much quicker.
> 4 votes

---
Tags: testing
---


# Question
Title: Remove taxes using Rules after coupon is redeemed
I'm attempting to create a rule that removes taxes from a line item after a Commerce Coupon is applied. Is there a way to do this?

# Answer
> 0 votes
Yes, there is a core Drupal Commerce Rules action called "Remove taxes applied to a line item" in the Commerce Tax group. Additionally, via Rules you can inspect field values on any entity to see if they are empty or not. The coupons applied to an order are tracked through a variable called commerce\_coupons.

Putting it all together, this means you need to create a custom product pricing rule that looks to see if the commerce\_coupons field is non-empty. If so, it should use the action mentioned above to remove taxes. Make sure the weight of your custom rule is set such that it is calculated after the discount that gets added via the coupon.

Note: this cannot be achieved through the Commerce Discount module's interface. It must be done via Rules at **Administration \> Store \> Configuration \> Product pricing rules**.

---
Tags: commerce
---


# Question
Title: URL to catch post data from off-site payment gateway in Drupal commerce
We have to set up an Drupal 7 e-commerce site with Commerce module (Kickstart) that accepts payments via an off-site payment gateway. For which we are developing a commerce payment method that will accept payments from the payment gateway.

Now, We are stuck at this step where this page is shown to a user:

```
example.com/store/checkout/[transaction id]/review

```

After selecting the payment method (that we developed) on the above review page, the page redirects to the payment gateway site. The Payment gateway site, after a payment attempt, sends the payment status to a response page via POST method.

Now, we don't know where to 'catch' the post data sent by the payment gateway in the payment method module.

Also, after the POST data is processed, how to update the `order/transaction` status in the database and show success/failure message to the user.

Any help would be appreciated.

# Answer
> 0 votes
You can catch it wherever you want. It's up to you to define the menu item and ensure it gets communicated properly to the gateway. See Commerce PayPal for examples - it uses an IPN listener that is always accessible (even in maintenance mode) and dispatches it to the appropriate payment method for processing.

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


title: Membership entity commerce join form

text:
# Question
Title: Membership entity commerce join form
I'm using Membership entity commerce (7.x-1.0-alpha2) for my website. On the join page, I'd like to reorder the membership types : I got "**one month**", "**three months**" and "**one year**", but they don't show up in the desired order... Plus I would like to customize this form (hide description and term length). I've been trying to change different things in the module's code with no luck. Any ideas ?

# Answer
First off, don't edit the module's code directly. Make a custom module that will hold your changes.

Secondly, you can use HOOK\_form\_alter to make changes to the form.
> 0 votes

# Answer
For others looking for the same thing : have a look at modules/membership\_entity/modules/membership\_entity\_type around line 16 you'll find the query that retrieve membership types : $ids = db\_query('SELECT id FROM {membership\_entity\_type}')-\>fetchCol(); I didn't know how to hook into this so I just added order by weight set the types weights through the UI and that worked good for me.
> 0 votes

---
Tags: commerce
---


title: Link node 1 to node 2 and create list

text:
# Question
Title: Link node 1 to node 2 and create list
I basically have a content type of companies and another of events. I would like to have a page with a select list of all companies and a select list of all events so that the user can choose what company is attending what event. This will need to allow multiple combinations.

**Example:** Company 1 will be at Event 1 and Event 2.

There will need to be list of all companies attending the selected event.

# Answer
This can be done using a combination of Editable Views and Entity Reference.

You will need to create an entity reference field on one of the content types that points to the other. Then create a view of that content type.

Using editable views you can have a select list to add an entity reference on the company node to the event node. If you set up the entity reference field to allow multiple values, you will be able to have one company attending multiple events.

You can also create a view that shows all entities that reference the the event in order to show a list of all companies who will be attending an event.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Popup dialog window based on selection in radio select list?
Use case:

A radio select list with Option A and Option B.

When User selects Option A, a popup appears with specific "A" message to verify the selection before User saves the page.

When User selects Option B, a popup appears with specific "B" message to verify the selection before User saves the page.

Suggestion on how to develop this? Hoping there's a module.

# Answer
> 0 votes
Since the popup appears as an immediate reaction to the user selection, this looks like a job for JavaScript or jQuery. Take a look at the jQuery Dialog user interface. And here is a tutorial on working with JavaScript within Drupal.

# Answer
> 0 votes
Like argiepiano says, use jquery. There's a few ways you could do it. You could either put a listener on each element, or on the div. For example, if you have radio buttons in a div with id `edit-my-radios`:

```
$(.edit-my-radios).change(function () {
  alert("You have selected "+ $( this ).find(":selected").text());
}

```

---
Tags: forms
---


# Question
Title: How to display a field before the title when the title was printed before the node template?
This answer works when the title is printed in the node template.

However, the base node template contains this code:

```
<?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
<?php endif; ?>

```

So how do I print a field before the title when the title was already printed in the page template?

# Answer
> 2 votes
`page.tpl.php` has a `$node` variable on all `node/%nid` pages. So you have two options:

1. You can use it directly in page.tpl.php (with the help of the `field_get_items()` and `field_view_field()` functions).
2. You can do your messing around with `$variables['node']` in a `THEME_preprocess_page()` function in your theme's `template.php`, then add your complete data to `$variables[]` to print the final value in `page.tpl.php`.

This may also help: Setting up variables in preprocess functions

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


# Question
Title: Split the node edit form into multiple pages (preferably using panels variants)
## The task

My goal is to split the node edit page with the main field forms staying on the default one (the add page itself or *mynodeurl*/edit), and some additional field forms on the other pages (e.g. *mynodeurl*/option & *mynodeurl*/otheroption).

I think the best way to do this (and the way I want it to work) would be using a couple of variants for the **node add/edit** page (**Panels Module**), with the url path's being filtered through the string: url path selection rules.

## The problem

I have no idea how to make the string url path selection rule work like that (I practically dont know anything how the string url path's selection rules work for the node (or node add\edit pages) at all, since I've only seen people implementing the url path based selection rules on custom pages and never on nodes).

## How I've tried to solve it

I've done some playing around setting url path's like: /option option */option nodetype/*/option etc. to the node template and the node add\edit form variants, the only thing that worked is when i set my main node view variant to trigger when: Current path is not "*/option" , and set the additional variant to trigger when Current path is "*/option", the exactly same thing didnt work for the node add\edit page. (see http://shot.faintrush.me/xfvu1c0aic.png \<- this screenshot).

The only working variant is using the Node template page, and adding forms there doesn't work which makes it useless for me. (**If you know how to make forms work on the Node template page you'r also very welcome to answer here**).

Of course the \*/option is probably not the best thing to put there, it's just the only one I found that's at least a bit alive.

## Additional info

By default my url's work as I have explained here -\> https://drupal.org/node/1993068 (i made those url aliases being created automatically but in a different way from using a pathauto + a custom token) To make the links like siteurl.com/nodetype/25/edit work i use the sub-pathauto module (i have tried setting the sub-pathauto url depth to 2 and accessing siteurl.com/nodetype/25/edit/option with the settings on the screenshot above - didn't work).

## More additional info

I also tried to make this work by creating a custom Page with the **/node/%node/option** path and assigning **%node** the **Node edit form: node ID** context, but then I'm running into another problem because the Node id doesn't actually match the url path and there's no way for me to assign the right context to the node edit form - the unique content type node id that i'm using in urls (again, read the issue from the link a bit higher) is not to get by any token or variable, the url alias is just being generated once by the rules module.

I posted the same issue (written in a little bit different words) to the drupal official website issue queue to the panels module but there seems to be no activity there for a couple of days so I'll give it a try here.

Any help would be appreciated!

# Answer
Please have a look at Multistep Nodeform.

> For each step you can define which fields should be included in this step. "Fields" includes core-fields like "Title", "Body" or "Authoring information" as well as fields defined by other modules (e.g. Date).
> 1 votes

# Answer
I don't fully understand the question, but there's a lot to cover, so here are some bits and pieces, and hopefully we can iron out something better from it.

For what it's worth, you refer to Panels, but it's Page manager that the question revolves around.

> I'm running into another problem because the Node id doesn't actually match the url path and there's no way for me to assign the right context to the node edit form

If you've come up with your own identifier scheme for you nodes, Page manager doesn't know about it. You can tell it, but implementing a new context type. See What are Ctools plugin (content type, access, etc), and how does one create them?.

> If you know how to make forms work on the Node template page you'r also very welcome to answer here

On node/%/edit, the edit form context is implicit, on node/% you can go to relationships and manually explicitly add it, but I don't see how that helps you. Plus using the node view to do node edit in general is weird.
> 0 votes

# Answer
The **Field Group module** can split the node edit form into horizontal tabs for example, under each one of them you can select which fields to show.

Here: https://www.drupal.org/project/field\_group
> 0 votes

# Answer
When you are testing the url, it tests the original path. So if your node/15 has an alias of match/christmas and you want to make the match/christmas/options use another panel, you can add a 'PHP code selection rule' to your panel. The way I've managed whas to print the args with dpm():

```
dpm(arg(0)); // node
dpm(arg(1)); // the node id, ex: 15
dpm(arg(2)); // options

```

Them I updated the code to:

```
if (arg(0) == 'node' && arg(1) == 'options') {
    return TRUE;
}
else {
    return FALSE;
}

```

And it worked =D

BUT putting php code isn't the best practice. SO I created a new "string URL path" selection rule with the path that now I know for sure that its being used.

```
node/*/options

```

Hope this helps =)
> 0 votes

---
Tags: 7, forms, panels
---


# Question
Title: How to programmatically change the weight of children in a taxonomy vocabulary?
I am trying to edit an existing vocabulary to change the weight of the children. Any idea?

# Answer
> 2 votes
Change the `weight` property on the term object.

```
$term = taxonomy_term_load($tid); //$tid = your taxonomy term id
$term->weight = 10000; //Whatever weight value
taxonomy_save_term($term);

```

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


# Question
Title: Granular role access on a per Entity basis
I have a config entity that I would like to grant access to on a role based level. There is going to be one role to access the entities, but how can I assign access on a *per* entity basis?

My naive thinking is to add a `$roles` array instance variable, and add each individual role to that, then create a custom `EntityAccessControlHandler` class, implementing `EntityAccessControlHandlerInterface` that checks the array for all of the users roles, but that doesn't seem like a very good solution.

# Answer
> but that doesn't seem like a very good solution.

Yes, it is.

What you're saying makes perfect sense, just do it :)

access() (or checkAccess()) is called for each entity separately, you can implement any imaginable logic in there, that's completely up to you.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Understanding the 'node' string in a Views SQL Query
I'm trying to understand this Views SQL Query:

```
    SELECT node.nid AS nid, node.title AS node_title, 'node' AS
field_data_field_icon_node_entity_type, 'node' AS
field_data_field_price_node_entity_type, 'node' AS
field_data_body_node_entity_type
    FROM
    {node} node
    INNER JOIN {field_data_field_type} field_data_field_type ON node.nid =
field_data_field_type.entity_id AND (field_data_field_type.entity_type =
'node' AND field_data_field_type.deleted = '0')
    WHERE (( (node.status = '1') AND (node.type IN  ('resource')) AND
(field_data_field_type.field_type_value = '4') ))
    ORDER BY node_title ASC
    LIMIT 10 OFFSET 0

```

Specifically, I need to know what the line in the SELECT statement that says 'node' AS field\_data\_field\_icon\_node\_entity\_type means.

I see in the database I have a field called 'field\_data\_field\_icon' but not with the rest of the jargon attached to it. So I'm not sure how it's getting that data.

Anyone know?

# Answer
> 6 votes
The 'node' string is a placeholder of sorts.

Internally, it indicates to Views that we are not going to attempt to fetch the requested field value in this SQL query itself. Instead, during the Views render process, the full node object is going to be loaded, and the output for that Views field is going to come from partially rendering the node object.

This allows Views to take full advantage of Drupal's field formatting system, which would be impossible on raw SQL values.

---
Tags: views, database
---


# Question
Title: WSOD afte uninstalling the Memcache module and deleting it's folder
I've uninstalled the Memcache API and integration module from my site and then deleted it's folder from `sites/all modules`.

Then, my site was down, and a WSOD appeared instead.

I went to Drush and typed `drush cc all`, and then this came up:

Afterwards I restored the deleted memcache folder at sites/all/modules, and again typed drush cc all... Then the site came to work, but now when I run Drush I still so something wired:

1. Why I have a WSOD when I remove the module's folder if the module itself doesn't even enabled?...
2. How can totally delete the module?

---

Update for user - Les Lim:

# Answer
One of the steps to install Memcache module is to add a line in your settings.php file that specifies a module file as a cache backend.

To uninstall the Memcache module, you will also need to remove that line in settings.php. Until then, Drupal will be attempting to load a cache backend from a file that is no longer there.
> 2 votes

---
Tags: caching
---


# Question
Title: How to display a video file without using the video hosting websides?
I need to display video file without using youtube, vimeo etc. I am using the bootstrap theme. I've tried to using some modules with no luck:

1. Module: MediaFront,
Field type: File,
Display mode: MediaFront Player
File is not rendering at all.
2. Module: Video,
Field type: Video
On Chrome looks fine, but there is a problem on Safari (can't debug it – tested on iPad).

I'm looking for some module/way that enables me to embed a responsive video.

# Answer
The Media project (https://www.drupal.org/project/media) has support for displaying uploaded video files using native HTML5.
> 0 votes

---
Tags: 7, theming, files
---


title: How do I convert drupal_goto to 301?

text:
# Question
Title: How do I convert drupal_goto to 301?
Right now I have a redirect in my code:

```
drupal_goto($path);

```

Per the documentation `drupal_goto` defaults to a 302 redirect. I want a 301.

However, when I put in:

```
drupal_goto($path, $http_response_code = 302);

```

It gives me an error:

> Argument 2 passed to drupal\_goto() must be of the type array, integer given,

But if I try something like:

```
drupal_goto($path, array $options = array(), $http_response_code = 302);

```

...I get this error:

> Unexpected '$options'

How can I properly change `drupal_goto` into a 301 redirect?

# Answer
Looks like you're mistaking the function definition for an implementation example.

The function definition describes the arguments to use, but it's not a literal example of how to call it.

So when you want to use the `drupal_goto()` function, instead of this:

```
drupal_goto($path, array $options = array(), $http_response_code = 302);

```

It should look more like this:

```
drupal_goto($path, array(), 301);

```
> 2 votes

# Answer
```
drupal_goto($path = '', array $options = array(), $http_response_code = 302)

```

Initialize $option as empty array something like this

```
$options = array();
$path = <your path>;
drupal_goto($path, $option, 301);

```
> 1 votes

---
Tags: 7, redirection
---


# Question
Title: WSOD and Drush cc all fail after deleting a view of a long-time-ago deleted module
## Background

Drupal 7.40 site, all is up2date, the site itself worked, until the last hour, just fine.

## The problem

I once had a module named Flexslider and have deleted it 5 months ago. One of it's views and/or content types stayed alive and I've deleted it in the last hour; Since then there is a WSOD in my site and each time I try to flush all caches with Drush I get the following error about the impossibility to access a Flexslider file.

Any ideas why would that happen?

---

Image update for user - Les Lim:

# Answer
Since I happen to know from WSOD afte uninstalling the Memcache module and deleting it's folder that you just stopped using Memcache, then I know that your Drupal site has just reverted back to using the database cache.

You probably had entries in your database cache from before you switched to Memcache in the first place. Those really old database cache entries are now back in use.

You're trying to clear caches, which is absolutely the correct thing to do. However, there's a nasty bug in CTools that prevents you from clearing the cache if a particular CTools cache entry is broken: https://www.drupal.org/node/1775612

In this case, though, the manual fix is pretty simple. You need to truncate the `cache` table in your database. That should allow the cache to rebuild itself normally.
> 1 votes

---
Tags: wsod, javascript
---


title: duplicate all instances of a term

text:
# Question
Title: duplicate all instances of a term
I'm trying to "clone" all nodes of a certain taxonomy term and assign them a new taxonomy term so they can function as sections of my site.

I'm making a site where i should put all of the information of a group of careers, something like: Contact, procedures, mission, syllabus, etc. (each on a page).

The thing is: the site should host like 16 different campuses, and about 150 careers. I'm using campus as a taxonomy term so i can group all careers of a campus, and i'm using another term to group every page of a certain career.

I don't want to create EVERY page of all of the careers, and i'm thinking there should be a way to duplicate a blank set of pages of a career and do a "batch duplicate".

I would appreciate any information that can point me in the right direction.

Thanks in advance.

# Answer
You can create a custom module and process all of your cloning via PHP code. This tutorial describes how to create a node programmatically by creating a new node object, `$node = new stdClass();` then assigning the various fields to it and then `node_save($node);`

So you can loop through your existing nodes that satisfy your condition, assign the existing node's fields to the new node, add any other custom fields you need, then save it, and when the loop is done you should have a new set of nodes.
> 0 votes

# Answer
I'm not sure I'm understanding this well, but perhaps you could create a new Content Type that holds all the career information that's common to all campuses. Then create a Content Type for each campus that has an Entity Reference field with unlimited cardinality (meaning that it allows you to have references to an unlimited number of careers). You can then create Views of campuses OR of careers with a relationship to the other Content Type, which will allow you to display the other Content Type fields in your table or list of nodes.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: ubercart template email addresses hard coded in template
I have inherited an app which has an email hard coded into an ubercart template here /sites/all/modules/ubercart/uc\_order/templates/uc-order--customer.tpl.php

How can I set up this email to be accessible from an adminitratable page instead of being hard coded so it can easily be changed?

# Answer
> 1 votes
There are 2 components here: capture/store a setting for you email & insert it into your template.

Since it's a part of your template settings, I'd suggest `hook_form_alter()` the order template setting form to capture/store a variable:

```
function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id) {
  $form['MYMODULE_uc_order_template_email'] = array(
    '#title' => t('Template Email'),
    '#default_value' => variable_get('MYMODULE_uc_order_template_email', 'test@example.com'),
    '#description' => t("Template Email"),
    '#type' => 'textfield',
  );
}

```

The next component is to take that variable an inject it into your template. Using the example above, the variable `MYMODULE_uc_order_template_email` will now be available. Use a pre-process function to insert a email variable into template. Add this to your theme's **template.php**:

```
function MYTHEME_preprocess_uc_order(&$variables) {
  $variables['my_email'] = variable_get('MYMODULE_uc_order_template_email', 'test@example.com');
}

```

Lastly, copy over **uc-order--customer.tpl.php** to your theme directory (so UC updates don't wipe away your customizations), flush the cache (to pickup the new template), and, insert `$my_email` into your **uc-order--customer.tpl.php** copy.

---
Tags: ubercart
---


# Question
Title: Pre-defined color picking in the node admin in Drupal 7
I want the user to select one of the predefined color for one my Article fields.

I am unable to find a suitable way for the user to do so though. What I want is that there is a color picker of selected colors and user is able to pick on.

Any idea ?

Thanks

# Answer
Like I said in my comment I'm having trouble understanding the actual question. If you want a user to be able to choose from a set of predefined colors and connect this value to a node of type `article` you could do like this:

* Visit `admin/structure/types/manage/article/fields`
* Add a new field of type `List (text)`
* Set the widget to `Selectlist` and press save
* On the next page under `Allowed values list` you then enter all your colors in the form `key|value` for instance `Red|Red` or `Black|Black` and then press `Save field settings`
* In the next form you might set if this field is required or not and a default value

Now your users can select a color from a select list on the article edit screen. Not sure this is what you're asking for though.

Here is an example of what the user will see when editing an article:
> 0 votes

# Answer
Color Field is the module which exactly meets your requirement.
> 0 votes

---
Tags: theming
---


# Question
Title: Customize Search Terms search criteria of the view
I am having a weird problem. I have made a exposed Filter "Search" field which allows a user to Search the results. It's a Search Term.

The problem is that it is not searching the results effectively.

**Example:** If I have a title **XYZ-0123** and I search for **XYZ**, it would not give this result.

Any idea how I can customize the Search Term?

I'd greatly appreciate if you can assist here.

## Here is a screenshot of the pop up in view. You can see there's no indication.

# Answer
> 0 votes
Select **Containg any word** operator in expose filter settings of Title field.

---
Tags: views
---


# Question
Title: How do I show only those node that have images available via a view?
I have a content type with image, title, and body fields. I created a view to show these things on front end. Here images are not available for all nodes of this content type.

I need to show only those nodes in front end that have images.

# Answer
> 2 votes
You can achieve it by following steps.

1. Add **Image** field filter criteria.
2. Now in configuration, select operator **Is not empty (NOT NULL)**.

---
Tags: 7, views
---


# Question
Title: Access field data in views row template (views 3)
So I checked Google for the past 2 hours because apparently something that was fairly simple back in the Views 2 days has changed in Views 3 (D7)... All attempts failed.

I have a view set to display as HTML list showing fields. One of those fields is an image field. I want to use the URL to the image file as inline style background-image on the LI element of the particular row.

In Views 2 I would have set the field to be excluded from display and then created a views template for the row and then used the $row variable to access the field information for the particular row. In Views 3 there only seems to be the $title and $options variable available and $row outputs only the rendered HTML for the whole row.

Long story short: How can I access the field data from inside a views-view-list--myview--page.tpl.php?

If anyone can help out, it is greatly appreciated.

# Answer
This is pretty simple. All you need to do is go through following steps, which will let you create a same type of view which I have created on my system: The trick is to use relationship from field\_image.

1. Create a simple view of articles (I created page), by default this will have a field\_image. I am exporting a view below, import it.
2. In theme information override style output from "views-view-list.tpl.php". I am attaching code for both.

View:

```
$view = new view();
$view->name = 'article_view';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Article View';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Article View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
/* Relationship: Content: Image (field_image:fid) */
$handler->display->display_options['relationships']['field_image_fid']['id'] = 'field_image_fid';
$handler->display->display_options['relationships']['field_image_fid']['table'] = 'field_data_field_image';
$handler->display->display_options['relationships']['field_image_fid']['field'] = 'field_image_fid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: File: Path */
$handler->display->display_options['fields']['uri']['id'] = 'uri';
$handler->display->display_options['fields']['uri']['table'] = 'file_managed';
$handler->display->display_options['fields']['uri']['field'] = 'uri';
$handler->display->display_options['fields']['uri']['relationship'] = 'field_image_fid';
$handler->display->display_options['fields']['uri']['label'] = '';
$handler->display->display_options['fields']['uri']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Article List */
$handler = $view->new_display('page', 'Article List', 'article_list');
$handler->display->display_options['path'] = 'article-view';

```

Now the overridden template:

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

?>
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>
    <h3><?php print $title; ?></h3>
  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; ?>" style="background-image:url(<?php print file_create_url($view->result[$id]->file_managed_field_data_field_image_uri); ?>);"><?php print $row; ?></li>
    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

```

This will do the trick for you. Let me know if you face some issues.
> 1 votes

# Answer
You can do this in views 3 without needing a template file.

1. Use Image URL Formatter then create a field in your view for the image, and format it as the image URL, and "exclude from display".
2. Create another field below the first, and go to the "rewrite results" field set, you can now use a token like \[image:url\] to print the result of the hidden field.
3. In that re-write results area, create your div and set the URL token as background.

> ```
> <div class="myfield" style="background:url('[image:url]')">
>  <p> Your Value </p>
> </div>
>
> ```

OR, without the Image URL Formatter module, I have just found another example here where you can..

1. Add a "File Usage: File" relationship (Advanced-\>Relationsips)
2. Add a "File: Path" field, NOT "Content: Image" (Block details-\>Fields)
3. You will have limitless options on image path output. Click to Display download path instead of URI.

**EDIT:**

I didn't know that views stripped inline styles. I use the field template, which is not actually used in views, but you can find a template in the theme folder of the views module. Rename views-view-field.tpl.php to views-view-field--yourfield.tpl.php and place the file in your themes template folder.

The hidden field you created for a formatted URL should now be available, and you can get it by...

```
$imageurl = $view->style_plugin->rendered_fields[$view->row_index]['yourimageurlfield'];
echo $imageurl;

```
> 0 votes

---
Tags: views, theming
---


title: Views slideshow fields

text:
# Question
Title: Views slideshow fields
I have an image field in my content type and I want to make a slideshow using the Views Slideshow module to show one image at a time.

If I put each image in a node of its own, the slideshow works fine. But can I have a slideshow using multiple images from the same field in the same node?

The point of this is that it is easier / quicker to create one node with 10 images than to create 10 different nodes. So far the slideshow seems to load all 10 images at the same time, but I want it to display only one image at a time.

# Answer
> 0 votes
Interesting question, but I wonder if the Views Slideshow module can do what you're trying to achieve. Therefor you may want to consider the alternative modules, as detailed below.

# Use the jCarousel module

Your question seems to be a variation of "Help with a Slideshow of Multiple Images in a Single Node", in which the Views Carousel module was recommended as a possible solution/alternative.

However the successor of that module in D7 is the jCarousel module. So maybe you want to give that module a try?

# Use the Field Slideshow module

Another module to consider as an alternative, is the Field Slideshow module. Here is a quote about it from its project page:

> Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.
>
> Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

This excerpt seems like pretty close to what is contained in the question details, no?

Curious to hear if either of these modules help somehow ...

# Answer
> 0 votes
You can also try flex slider.

Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device

## FlexSlider features

* Using Fields and Views with FlexSlider
* sliders as navigation for other sliders
* Using carousels
* Using captions

---
Tags: views
---


# Question
Title: How to change the output of a theme function?
I know this question already has some "kind" of answer in documentations but they are too abstract for me. Most documentation I have seen on Drupal doesn't explain all the details of how to properly override a theme function, or maybe I don't understand.

My problem is that I need to change the output of theme function `theme('links__system_main_menu', ...)`, which is used in `page.tpl.php` to print the content of the main menu. I don't understand how to make it done. Please explain me every step you take and why did you take that step.

# Answer
> 0 votes
To override the output of a theme function in a theme, you simply take the name of your theme, and the name of the theme function, and join them together with an underscore.

So for your example, the function would be called:

```
function MYTHEME_links__system_main_menu($variables) {
  $html = '<ul>';

  // Loop over links

  $html .= '</ul>';

  return $html;
}

```

Your function should return the HTML string that you want to be rendered when this theme is used, any variables that have been passed to the `theme()` function will be available to you in `$variables`.

Usually it's enough to look at the original theme function to find out what's available to build your HTML, but sometimes you'll need to get the Devel module installed and inspect vars with `dpm` to properly see what's going on.

---
Tags: theming
---


# Question
Title: INPUT query for cache_menu returns mysql #2006 error in MAMP
This actually happens when I want to import a db from a live site to a local site in MAMP.

Running mac osx 10.6.8 and MAMP 2.0.5.

I googled this mysql error and most people seem to have this solved by increasing the `memory_limit` value in `/Applications/MAMP/bin/php5.3.6/conf/php.ini`. I set it to `512M`. And yes I made sure MAMP is running php 5.3.6.

...anyway increasing the memory size didn't solve the issue obviously

then I went looking at the error logs under `Applications/MAMP/logs/php_error.log` and `Applications/MAMP/logs/mysql_error_log.err` but both don't have any recent log information at all actually which is quite bizarre as well.

What I can also tell you is that the last `VALUE` which the query wants to `INSERT INTO 'cache_menu'` is very very large.

Here's the query that gives the #2006 error:

```
INSERT INTO `cache_menu` (`cid`, `data`, `expire`, `created`, `headers`, `serialized`) VALUES ('links:admin_menu:tree-data:9942fb041052f49f910af3e0190b9115', 0x613a323a7b733a343a2274726565223b613a31303a7b693a333635313b613a323a7b733a343a226c696e6b223b613a33373a7b733a31343a226c6f61645f66756e6374696f6e73223b4e3b733a31363a22746f5f6172675f66756e6374696f6e73223b4e3b733a31353a226163636573735f63616c6c6261636b223b4e3b733a31363a226163636573735f617267756d656e7473223b4e3b733a31333a22706167655f63616c6c6261636b223b4e3b733a31343a22706167655f617267756d656e7473223b4e3b733a353a227469746c65223b4e3b733a31343a227469746c655f63616c6c6261636b223b4e3b733a31353a227469746c655f617267756d656e7473223b4e3b733a343a2274797065223b4e3b733a31313a226465736372697074696f6e223b4e3b733a393a226d656e755f6e616d65223b733a31303a2261646d696e5f6d656e75223b733a343a226d6c6964223b733a343a2233363531223b733a343a22706c6964223b733a313a2230223b733a393a226c696e6b5f70617468223b733a373a223c66726f6e743e223b733a31313a22726f757465725f70617468223[...]

```

# Answer
> 0 votes
Backup and migrate exports the database automatically without (large) values in the cache\_menu table. Thus, re-exporting the database using the backup and migrate module solved the issue.

# Answer
> 0 votes
\[Solution\] It is always advised when you are importing your drupal site at a destination, so before exporting the db from the source, first clear cache if your don't it will cause the above error on cache\_menu table

Solution : Go to your exported .sql file open it in editor and remove any thing that is in the section

--

## -- Dumping data for table `cache_menu`

NOTE: cache\_menu should be enclosed in mysql's sql quotes for tables

# Answer
> -1 votes
MySQL-\>my.ini max\_allowed\_packet = ...

---
Tags: 6, database
---


# Question
Title: How to use an omega template with hook_theme
I'm using page callback function to display a page. How would I change this to use an omega template? I've tried adding a vis.tpl.php to the omega templates function but to no avail. I don't understand how to declare a omega template for use with a particular page.

```
<?php

function vis_menu() {

  $items['images'] = array(
    'title' => 'Images',
    'page callback' => 'image_page',
    'access callback' => TRUE,
  );
  return $items;
}

function image_page() {
  return 'hello';
}

```

Any help would be much appreciated.

# Answer
> 0 votes
I solved this using this question as a basis to work from https://stackoverflow.com/questions/4100485/register-your-theme-functions-in-drupal.

The template (.tpl.php file) goes in the omega template directory. You then use a `hook_theme` function to define the theme with the template key in the array pointing to the name of your template file.

The theme is then called with `theme(your-theme-name)`

Here's my working example for my module called `vis`:

```
function vis_menu() {

  $items['images'] = array(
    'title' => 'Images',
    'page callback' => 'image_page',
    'access callback' => TRUE,
  );
  return $items;
}

function image_page() {
  return theme('images');
}

function vis_theme() {
  return array(
    'images' => array(
      'variables' => array(),
      'template' => 'vis',
    ),
  );
}

```

---
Tags: 7, theming
---


# Question
Title: Not able to post comment anonymously: getting 403 error
I am working on phonegap app and using drupal 7 as backend for all json request data. I am using the service module for it. At frontend I am using Angular js in phonegap.

I referred http:// drupal.stackexchange.com/questions/22277/creating-comments-and-nodes-with-services-3-x-and-json for posting comment.

I set permission for anonymous user to post comment to any node from drupal permission section. But its not posting any comment. Giving me error.

> /appapi/comment.json 403: Access denied for user anonymous

Here is my code:

```
var dataObj = {"subject":$comment.text, "comment_body":{"und":[{"value":$comment.text}]}, "nid":$comment.nid} ;

var res = $http.post($scope.apiBaseUrl+'/appapi/comment.json', dataObj,{ withCredentials: false, headers: { 'Content-Type': 'application/json'} }); res.success(function(data, status, headers, config)
{ //$scope.message = data;
console.log(data);
 });

```

Here is CROS module setting:

```
*|*|POST,GET,PUT,DELETE|Origin, X-Requested-With, Content-Type, Accept|false

```

I am sending comment post request from phonegap app. I am not using the AgularJS module.

# Answer
Thanks tyler.frankenstein. Thanks for suggesting angular-drupal. I integrated it with my agularjs ui and its working superb.

I gone through angular-drupal code and found that it need X-CSRF-Token in header for write operation. Accordingly i modified my CORS setting

```
*|*|POST,GET,PUT,DELETE|Origin, X-Requested-With, X-CSRF-Token, Content-Type, Accept|false

```

And used agular-drupal method to save comment. Here is my code.

```
//register drupal service as provider/injector
.factory('$drupal',['drupal', function(drupal) {
  return drupal;
}])
.
.
.
//inside controller

.controller('HomeCtrl', function($scope, $stateParams,$http,$state,$drupal) {

  $drupal.node_load(27).then(function(node) {
    console.log(node.title);
    alert(node.title);
  });

  var comment = {
  nid: 27,
  subject: 'Hello world',
  comment_body: { und: [ { value: 'How are you?' } ] }
};
$drupal.comment_save(comment).then(function(data) {
    alert('Created comment: ' + data.cid);
});

```

Other way to achieve this without angular-drupal is to generate x-csrf-token using get request "/?q=services/session/token" and then set it in header for your post request.

Thank you.
> 0 votes

---
Tags: services, javascript
---


# Question
Title: Switch default bootstrap styles with different ones
I have this site that's using a subtheme of Drupal Boostrap theme. The contents are mainly made with views. I want to change the look of the table on the link with the style of the condensed table on this boostrap template

How can I achieve this? Do I define the css to use in views? Should I change the style.css in my subtheme to override the default css with the new one? Should I copy the css files of the new theme?

I'm really lost on how to apply the styles to the subtheme. Can someone guide me on how to do it or if there's some kind of tutorial for this particular case: Bootstrap Template do Drupal Theme.

Thanks.

# Answer
I think you could approach this issue with any of the solutions you just mentioned. If it's just a table you are theming, I don't know that I would necessarily go through the trouble of creating an entirely new theme or sub-theme for just that component. Can you use the bootstrap styles and simply integrate them into your site with different class names?
> 0 votes

---
Tags: theming
---


title: Grid mode doesn't work

text:
# Question
Title: Grid mode doesn't work
I've created a view of fields and filtered it via content type. The content itself is taken from the node, but it won't show the grid.

Why doesn't the grid work?
Can I show the grid only for certain fields and not to all of them?

>

>

>

# Answer
1. Your theme could be breaking the grid. Grid's are usually tables, so they generally work regardless of the theme - but if your theme is making any modifications to it the grid may break. I would suggest examining the HTML code that is being generated for the grid (in Chrome: right click the grid and select Inspect Element). Make sure that it's a table... and also examine the styles applied to it to see if any of them are breaking the normal grid display.
2. No - you can't tell Views to put certain fields in the grid and certain fields outside of it. I can't really imagine how that would work, or what you mean by that exactly, so it's hard to suggest an alternative. Perhaps two separate Views?
> 0 votes

---
Tags: views
---


# Question
Title: Multiple menu locations in taxonomy menu
I've used taxonomy menu version 7.x-1.5. Due to this module I can only added taxonomy menus into single menu location.

But I want to add a taxonomy menu into multiple menus. Is it possible? If yes, how to do this?

I've attached image. Please look it.

# Answer
> 0 votes
You can manually add menu items that link to the taxonomy terms as many times as you want - but that Taxonomy Menu option will only manage a single one.

You could potentially write a custom module that automatically inserts the same item into other menus at the same time - but that might be more complicated than you want.

---
Tags: taxonomy-terms
---


# Question
Title: Not sure how to work with beanstalkd module
I am looking to setup a queue system to upload large files (~150MB). For specific reasons we decided to do this using SFTP (phpseclib). After some research I came to the conclusion that I would probably need something like a work queue. I decided to go with Beanstalkd since there was a drupal module for it.

I have managed to get a Beanstalkd server running and add items to the queue. But now I'm kind of confused as to how I would need to execute a specific script.

Can anyone help with this particular part of getting beanstalkd queue items to run in a non-blocking way?

Do I need to maybe write a shell script to run a php cli or am I looking at it all wrong?

# Answer
> 0 votes
I managed to figure it out.

Using hook\_cron\_queue\_info, it is possible to define worker callbacks for queue items.

I then wrote the sftp upload script in the worker callback and then run the runqueue.sh script that comes with the drupal beanstalkd module to listen for ready queue items.

# Answer
> 0 votes
In case anyone stumbles on this question looking for a Drupal 8 solution, the process changed: hook\_cron\_queue\_info() got renamed to hook\_queue\_info(), then replaced by worker plugins. So, in 8.0.0-rc2 and later, you need to create a worker class as a QueueWorker plugin, placing it in your module's `src/Plugin/QueueWorker` directory, and adding it the needed annotations, like this example taken from the `SampleWorker` example provided in the Beanstalkd module:

```
<?php
/**
 * Pretend to perform some work.
 *
 * @QueueWorker(
 *   id = "beanstalkd_example",
 *   title = @Translation("Beanstalkd example worker"),
 *   cron = {"time" = 60}
 * )
 */
class SampleWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {
// ...
?>

```

---
Tags: drush, cron
---


# Question
Title: REST call using curl taking to much time. Show as progress bar
I'm getting information from a source using REST. Bellow is part of my code. Basically, there's a part where I have a `for loop` that can take 30 to 60 seconds to complete. It works but the user doesn't have feedback if the date is being fetched.

```
<?php
    function get_data($qc, $path) {
        $qc = curl_init();

        for ($i = 0; $i < sizeof($myarray); $i++) {
            curl_setopt($qc, CURLOPT_URL, "http://myurl/" . $path[$i] . "]}");

            $xml = simplexml_load_string(curl_exec($qc));
            $json = json_encode($xml);
            $output_array = json_decode($json, TRUE);

            ...
        }
        return $output_array;
    }
?>

```

Is there a way that I can do this asynchronously? Show a progress bar or something?

I looked at this module - Background Process but I think this is not the way to do it.

Note: I know the size of `$myarray`

Thanks.

EDIT: Added all the code to the question:

```
<?php
function mymodule_menu() {
    $items = array();
    $items['home/QC'] = array(
        'title' => 'QC',
        'description' => 'QC Test',
        'menu_name' => 'main-menu',
        'access callback' => TRUE,
        'page callback' => 'mymodule_qc',
    );
    return $items;
}

function mymodule_qc() {
    //create a new cURL resource
    $qc = curl_init();
    //create a cookie file
    $ckfile = tempnam ("/tmp", "CURLCOOKIE");

    //set URL and other appropriate options
    curl_setopt($qc, CURLOPT_URL, "http://myurl:port/qcbin/rest/is-authenticated");
    curl_setopt($qc, CURLOPT_HEADER, 0);
    curl_setopt($qc, CURLOPT_HTTPGET, 1);
    curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);

    //grab the URL and pass it to the browser
    $result = curl_exec($qc);
    $response = curl_getinfo($qc);

    if($response['http_code'] == '401') {
        $url = "http://myurl:port/qcbin/authentication-point/authenticate";
        $credentials = "username:password";
        $headers = array("GET /HTTP/1.1","Authorization: Basic ". base64_encode($credentials));

        curl_setopt($qc, CURLOPT_URL, $url);
        curl_setopt($qc, CURLOPT_HTTPGET,1); //Not sure we need these again as set above?
        curl_setopt($qc, CURLOPT_HTTPHEADER, $headers);
        //Set the cookie
        curl_setopt($qc, CURLOPT_COOKIEJAR, $ckfile);
        curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($qc);
        $response = curl_getinfo($qc);

        //The response will be 200
        if($response['http_code'] == '200') {
            $out = "Authentication OK!";
            //Use the cookie for subsequent calls...
            curl_setopt($qc, CURLOPT_COOKIEFILE, $ckfile);
            curl_setopt($qc, CURLOPT_RETURNTRANSFER, true);

            $name = "QC FOLDER NAME";
            $safe_name = rawurlencode($name);

            curl_setopt($qc, CURLOPT_URL, "http://myurl:port/qcbin/rest/domains/MYDOMAIN/projects/MYPROJECT/test-set-folders?query={name['" . $safe_name . "']}");

            //In this example we are retrieving the xml so...
            $xml = simplexml_load_string(curl_exec($qc));
            $json = json_encode($xml);
            $out_array = json_decode($json, TRUE);

            $id = $out_array['Entity']['Fields']['Field'][0]['Value'];
            $path = $out_array['Entity']['Fields']['Field'][6]['Value'];

            // Get Test Sets:
            $testsets = get_testsets($qc, $path);

            // Save data to Drupal Database:
            xreport_qc_savedata($testsets);

            //Call Logout
            logout($qc,"http://myurl:port/qcbin/authentication-point/logout");
        }   else {
            $out = "Authentication failed";
        }
    }   else {
        $out = "Not sure what happened?!";
    }

    //Close cURL resource, and free up system resources
    curl_close($qc);
}

function get_testsets($qc, $path) {
    // GET TEST SETS:
    curl_setopt($qc, CURLOPT_URL, "http://myurl:port/qcbin/rest/domains/MYDOMAIN/projects/MYPROJECT/test-sets?query={test-set-folder.hierarchical-path[" . $path . "*]}");

    $xml = simplexml_load_string(curl_exec($qc));
    $json = json_encode($xml);
    $out_array = json_decode($json, TRUE);

    // Get all names and ids of testsets:
    $testsets = array();
    if (isset($out_array['Entity'][0])) {
        foreach ($out_array['Entity'] as $folder) {
            $id = $folder['Fields']['Field'][51]['Value'];
            $name = $folder['Fields']['Field'][54]['Value'];

            $testset = array($id, $name);
            array_push($testsets, $testset);
        }
    } else {
        $id = $out_array['Entity']['Fields']['Field'][51]['Value'];
        $name = $out_array['Entity']['Fields']['Field'][54]['Value'];

        $testset = array($id, $name);
        array_push($testsets, $testset);
    }

    for ($i = 0; $i < sizeof($testsets); $i++) {
    #for ($i = 33; $i < 34; $i++) {
        curl_setopt($qc, CURLOPT_URL, "http://myurl:port/qcbin/rest/domains/MYDOMAIN/projects/MYPROJECT/test-instances?query={cycle-id[" . $testsets[$i][0] . "]}");

        $xml = simplexml_load_string(curl_exec($qc));
        $json = json_encode($xml);
        $testset_array = json_decode($json, TRUE);

        if (isset($testset_array['Entity'])) {
            $x = 0;
            if (isset($testset_array['Entity'][0])) {
                foreach ($testset_array['Entity'] as $testset) {
                    $testcase_id = $testset['Fields']['Field'][70]['Value'];
                    $testcase_week = $testset['Fields']['Field'][22]['Value'];
                    $testcase_mrid = $testset['Fields']['Field'][25]['Value'];
                    $testcase_build = $testset['Fields']['Field'][31]['Value'];
                    $testcase_status = $testset['Fields']['Field'][63]['Value'];

                    // Adds the TestSet Name to the same array level:
                    $testsets[$i][3][$x]['testcase_testset'] = $testsets[$i][1];
                    $testsets[$i][3][$x]['testcase_id'] = $testcase_id;
                    $testsets[$i][3][$x]['testcase_week'] = $testcase_week;
                    $testsets[$i][3][$x]['testcase_mrid'] = $testcase_mrid;
                    $testsets[$i][3][$x]['testcase_build'] = $testcase_build;
                    $testsets[$i][3][$x]['testcase_status'] = $testcase_status;

                    // Get testcase details:
                    $link = "http://myurl:port/qcbin/rest/domains/MYDOMAIN/projects/MYPROJECT/tests/" . $testcase_id;
                    curl_setopt($qc, CURLOPT_URL, $link);

                    $xml = simplexml_load_string(curl_exec($qc));
                    $json = json_encode($xml);
                    $testcase_array = json_decode($json, TRUE);

                    $testcase_name = $testcase_array['Fields']['Field'][92]['Value'];
                    $testsets[$i][3][$x]['testcase_name'] = $testcase_name;
                    $x += 1;
                }
            } else {
                $testcase_id = $testset_array['Entity']['Fields']['Field'][70]['Value'];
                $testcase_week = $testset_array['Entity']['Fields']['Field'][22]['Value'];
                $testcase_mrid = $testset_array['Entity']['Fields']['Field'][25]['Value'];
                $testcase_build = $testset_array['Entity']['Fields']['Field'][31]['Value'];
                $testcase_status = $testset_array['Entity']['Fields']['Field'][63]['Value'];

                // Adds the TestSet Name to the same array level:
                $testsets[$i][3][$x]['testcase_testset'] = $testsets[$i][1];
                $testsets[$i][3][$x]['testcase_id'] = $testcase_id;
                $testsets[$i][3][$x]['testcase_week'] = $testcase_week;
                $testsets[$i][3][$x]['testcase_mrid'] = $testcase_mrid;
                $testsets[$i][3][$x]['testcase_build'] = $testcase_build;
                $testsets[$i][3][$x]['testcase_status'] = $testcase_status;

                // Get testcase details:
                $link = "http://myurl:port/qcbin/rest/domains/MYDOMAIN/projects/MYPROJECT/tests/" . $testcase_id;
                curl_setopt($qc, CURLOPT_URL, $link);

                $xml = simplexml_load_string(curl_exec($qc));
                $json = json_encode($xml);
                $testcase_array = json_decode($json, TRUE);

                $testcase_name = $testcase_array['Fields']['Field'][92]['Value'];
                $testsets[$i][3][$x]['testcase_name'] = $testcase_name;
                $x += 1;
            }
        } else {
            // testset is empty
        }
    }
    return $testsets;
}

function logout($qc, $url) {
    curl_setopt($qc, CURLOPT_URL, $url);
    curl_setopt($qc, CURLOPT_HEADER, 0);
    curl_setopt($qc, CURLOPT_HTTPGET,1);
    curl_setopt($qc, CURLOPT_RETURNTRANSFER, 1);

    //grab the URL and pass it to the browser
    $result = curl_exec($qc);
}

function xreport_qc_savedata($testsets) {
    foreach ($testsets as $testset){
        if(isset($testset[3])) {
            $newarray = $testset[3];
            foreach ($newarray as $value){
                if (!empty($value['testcase_id'])) {$testcase_id = $value['testcase_id'];} else {$testcase_id = '';}
                if (!empty($value['testcase_testset'])) {$testcase_testset = $value['testcase_testset'];} else {$testcase_testset = '';}
                if (!empty($value['testcase_name'])) {$testcase_name = $value['testcase_name'];} else {$testcase_name = '';}
                if (!empty($value['testcase_week'])) {$testcase_week = $value['testcase_week'];} else {$testcase_week = '';}
                if (!empty($value['testcase_mrid'])) {$testcase_mrid = $value['testcase_mrid'];} else {$testcase_mrid = '';}
                if (!empty($value['testcase_build'])) {$testcase_build = $value['testcase_build'];} else {$testcase_build = '';}
                if (!empty($value['testcase_status'])) {$testcase_status = $value['testcase_status'];} else {$testcase_status = '';}

                $node = new stdClass();
                $node->type = 'content_qc';
                $node->language = LANGUAGE_NONE;
                node_object_prepare($node);

                $node->title = $testcase_id;
                $node->field_x_qc_testcase_id[$node->language][]['value'] = $testcase_id;
                $node->field_x_qc_testset[$node->language][]['value'] = $testcase_testset;
                $node->field_x_qc_testcase_name[$node->language][]['value'] = $testcase_name;
                $node->field_x_qc_week[$node->language][]['value'] = $testcase_week;
                $node->field_x_qc_mrid[$node->language][]['value'] = $testcase_mrid;
                $node->field_x_qc_build[$node->language][]['value'] = $testcase_build;
                $node->field_x_qc_status[$node->language][]['value'] = $testcase_status;
                $node->status = 1;

                node_save($node);
            }
        } else {
            // no testcases on the current testset
        }
    }
}

```

# Answer
Sure. You could use the Batch API and create processes to handle your operations asynchronously. The progress bar will be automatically displayed as the processes are completed.

See an example here: Using the Drupal Batch API
> 1 votes

---
Tags: 8
---


# Question
Title: Views - D7 - Filtering by authorname only works with admin role
I've created a view which is displaying time tracking information. Everything works great except one thing and I can't figure out what the issue is. I have an exposed filter which filters by authorname. The filter by default is an autocomplete text field. When I am logged in as an admin role, the autocomplete works as it should, however when I am logged in as an authenticated user, that filter stops working. All my other exposed filters work, except this one. I am assuming it is a permissions issue, but I cannot for the life of me figure out what I need to enable to allow a regular user use this filter.

Any suggestions would be appreciated. I am using D7 with Views.

# Answer
> 0 votes
I just installed the Administration Views module and ran into this issue. Setting the "View user profiles" permission fixed the problem. Thanks @Marius Ilie.

---
Tags: views, ajax
---


title: Using LIKE in search query

text:
# Question
Title: Using LIKE in search query
I would like to search for words that **contains** the keyword when a user executes a search. I have tried to hook into `hook_query_alter()`:

```
function MYMODULE_query_alter(&$query) {
  // Check if this is a search query
  if (!$query->hasTag('search_node')) {
    return;
  }

  $conditions = &$query->conditions();
  $conditions = &$conditions[1]['field']->conditions();
  // Change the condition to '%<keyword>%'
  // and add LIKE as operator
  $conditions[0]['value'] = "%" . $conditions[0]['value'] . "%";
  $conditions[0]['operator'] = 'LIKE';
}

```

I can alter the search query, but I'm not getting any results.

The modified query that gets executed looks like this:

```
SELECT FROM {search_index} i
  INNER JOIN {node} n ON n.nid = i.sid
  INNER JOIN {search_total} t ON i.word = t.word
  WHERE (n.status = :db_condition_placeholder_0)
    AND ((i.word LIKE :db_condition_placeholder_1 ESCAPE '\\'))
    AND (i.type = :db_condition_placeholder_2)
  GROUP BY i.type, i.sid
  HAVING  (COUNT(*) >= :matches)

```

And the placeholders in the `SelectQuery` object are set to:

```
[:db_condition_placeholder_0] => 1
[:db_condition_placeholder_1] => %liv%
[:db_condition_placeholder_2] => node

```

I can verify that the tables `search_index` and `search_total` both contain a couple of words that contain `liv`, so this should return some results.

I have also tried Fuzzy Search module, but I don't know how I can connect the provided search to the ordinary search form.

Notice that I have tried `db_like()`, but without any success.

I don't understand why it should be so hard to change the default search to search through the index using a `LIKE` rather than `=` condition?

Something like this should work if I only knew how to implement it:

```
$keyword = $_GET['s'];
$status = 1;
$types = array('article', 'contact');

db_query("SELECT node.nid FROM {node} n
  INNER JOIN {search_index} si
    ON si.sid = n.nid
    AND si.word LIKE :keyword
  INNER JOIN {search_dataset} sd ON sd.sid = n.nid
  WHERE n.status = :status AND n.type IN (:types)
  GROUP BY n.nid", array(
    ':keyword' => '%' . db_like($keyword) . '%',
    ':status' => $status,
    ':types' => $types
  )
);

```

# Answer
> 1 votes
you connect the the fuzzy search via search api pages module (or views).

when using views you can place the views search block in your desired region.

Manual instructions: (from fuzzy search)

* From the main Search API configuration page, create a server using the Fuzzy Search service class.
* Create an Index using the server you just created.
* Click the Workflow Tab.
* Enable "Complete entity view".
* Enable the following processors: Both Fuzzy search processors, Ignore case, HTML filter, and Tokenizer.
* Move the Fuzzy Search excerpt processor to the bottom of the list, and the Fuzzy Search search settings processor just above it.
* The default settings should be fine.
* You will need the Search API Pages module or Views to provide a place to search your site.
* Go to the main Search API page,
* Click Search Pages, add a search page, and configure with the index you created above, multiple terms for query type, and view mode as themed as search results.
* For Views, make a new view using the default fuzzyseach index, add a page display and configure as desired.
* Run cron to index your content. Visit the path for your search page.

# Answer
> 1 votes
You get no results with your altered query because of what `SearchQuery::parseSearchExpression()` does to it. Specifically, around line 300:

```
// Single ANDed term.
else {
  ...
  $this->conditions->condition('d.data', "% $key %", 'LIKE');
  ...
}

```

Notice the spaces in the condition.

To get any results you'd have to remove those spaces from the query which isn't a simple task. I believe something like this would be required:

```
function my_module_query_alter($query) {
  if ($query->hasTag('search_node')) {
    $conditions = &$query->conditions();
    $conditions = &$conditions[1]['field']->conditions();
    $conditions[0]['value'] = '%' . $conditions[0]['value'] . '%';
    $conditions[0]['operator'] = 'LIKE';
  }

  if ($query instanceof PagerDefault) {
    PagerDefaultHelper::alter($query);
  }
}

class PagerDefaultHelper extends PagerDefault {
  public static function alter(PagerDefault &$query) {
    $search_query = &$query->query;
    SearchQueryHelper::alter($search_query);
  }
}

class SearchQueryHelper extends SearchQuery {
  public static function alter(SearchQuery &$query) {
    $conditions = &$query->conditions->conditions();
    $conditions[0]['value'] = str_replace(' ', '', $conditions[0]['value']);
  }
}

```

However, this will only work when searching for a single word. You would have to build on this approach for searches that use multiple words, OR'd words or excluded words.

# Answer
> 0 votes
I think if I add **db\_like($prefix)** using db\_like may be it worked!

```
(i.word LIKE :db_condition_placeholder_1 ESCAPE '\\')

Convert into:

 condition('i.word', db_like($prefix) . '%', 'LIKE')

```

I am not expert in customization but may be it helpful for you!

# Answer
> 0 votes
I'm not sure that this is the best way to solve this problem, but I ended up using `hook_node_update_index()` to support searching for parts of words:

```
function hook_node_update_index($node)
{
   $result = '';

   // how long should each part be?
   $options = array(3, 4, 5);

   // only look at the body and title
   $content = $node->body['und'][0]['value'] . ' ' . $node->title;
   $content = strip_tags($content);
   $content = drupal_strtolower($content);

   $words = explode(' ', $content);

   $parts = array();

   // split words into parts
   foreach ($words as $word) {
     // if the length is less than the size we would like to split at
     // then there's no need to continue
     $length = drupal_strlen($word);

     foreach ($options as $option) {
        if ($length < $option) {
           $result .= ' ' . $word;
           break;
        }
        for ($i=0; $i < ($length - $option + 1); $i++) {
           $parts[] = drupal_substr($word, $i, $option);
        }
     }
   }

   // append all created parts for the words
   if(count($parts)) {
      $result .= ' ' . implode(' ', $parts);
   }

   return $result;
}

```

From the documentation:

> **function hook\_node\_update\_index**
>
> Act on a node being indexed for searching.
>
> This hook is invoked during search indexing, after node\_load(), and after the result of node\_view() is added as $node-\>rendered to the node object.

I add this as an answer, since it might help someone in the future. I still looking for a better solution that uses a `LIKE` conditions for each keyword.

---
Tags: 7, search, database
---


# Question
Title: Bootstrap theme: editing the registration page
I am new to Drupal and wondering how to edit the look and feel of the registration page form? For what it's worth, I'm using the Bootstrap theme. I'd usually do this via CSS; however, with Drupal this is somewhat tricky. The problem is the form fields are expanding to fill their container, and, as you can imagine, it looks pretty ridiculous having a username field filling 3/4 of the screen. Looking at the elements `class` shows no clues as it is not a standard Bootstrap class (must be Drupal generated I imagine). I have edited the *basic page* content type in an attempt to make it work - but as I have learnt: the registration page is not styled from basic page. Any help would be great, thanks!

# Answer
> 1 votes
Take a look at drupal api documentation. Customizing forms is quite easy. https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_FORM\_ID\_alter/7

Just hook into that user\_registration\_form and for example add into class index bootstrap classes col col-lg-\*. Or you can add #prefix and #suffix to wrap things into columns etc. And install Devel module to examine form's structure.

I'm not sure if it possible to use page--user--register.tpl.php to modify layout. Possibly you could create that and add col col-lg-offset-\* col-lg-\* to whatever element is the container for page\[content\] variable.

---
Tags: users, theming
---


# Question
Title: How to show user profle edit tab as a default tab on user profile page?
I want to show user profile edit tab as a default, on page load its content must show. Like we have option in quick tab module, in which you can select which tab must show on page load.

How to perform this?

# Answer
> 1 votes
You could use the Redirect module to redirect users from /user/\* to /user/\*/edit. This could cause problems when other users are trying to view other user's profiles.

You can also do this with Rules. This would allow you to redirect users conditionally.

---
Tags: users, hooks
---