# Question
Title: Creating a user using Services results in user not being able authenticate using HTTP Basic Auth
I'm developing a backend for an Android application using Drupal, and I've run into somewhat of a weird problem. I'm using Services and Views for the input and output of various content types. In order to make requests to the Services module, the users need to authenticate using HTTP Basic authentication.

When users create a new account in my app, I use the Services endpoint to create the new account using data that the user enters himself. However, the password that gets send to the endpoint is not the same as the password that gets saved. This results in users not being able to authenticate other requests using HTTP Basic Auth with the password they set, as Drupal does not recognize the password. However, logging in using the Services endpoint DOES work with the set password.

When changing this user's password manually in the Administration panel to the value they set in the app, the HTTP Basic auth requests suddenly work, and they can still login using the Services module as well.

What's going wrong here, and even better, what can I do to remedy this problem? I'm not looking forward to changing every user's password manually so they can use the rest of my backend, and dropping the HTTP Basic Authentication is not an option either.

Edit:

Further investigation has shown that it's also not possible to login to the Drupal frontend using an account created by the Services endpoint, unless you change the password manually.

# Answer
> 1 votes
@Sander van't Veer - I struggled with this same problem recently. It looks like there's a bug in the services module where the password doesn't get set. Try this patch and you should be good.

https://drupal.org/files/issues/user\_create-2198005-1.patch

---
Tags: services, users
---


# Question
Title: Get term plain text aliased url from tid
I realise that this is similar to other questions posted, but they all seem to involve using `print l()` to output a fully formed anchor.

What I need is just the uri, output in plain text to use directly in the node template. I nearly got there with the following, but end up with the unaliased version:

```
<?php
  if (isset($node->field_source_of_tid['und'][0]['tid']) && $node->field_source_of_tid['und'][0]['tid']) :
    $term=taxonomy_term_load($node->field_source_of_tid['und'][0]['tid']);
    $term_uri = taxonomy_term_uri($term);
    $output = $term_uri['path'];
endif; ?>

```

And I use the output as so:

```
<a href="<?php print render($output); ?>">A BUTTON </a>

```

Any ideas?

Thanks!

# Answer
> 1 votes
You're probably looking for `url()`

> Generates an internal or external URL.

e.g.

```
$output = url($term_uri['path']);

```

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


# Question
Title: Auto approve an user after registration (Services)
Is there some way to auto approve an user after registration? I don't want to send any email confirming the email or changing the password.

I'm trying to build a register/login for an app with REST services, but I don't want the user have to check the email to change the password, I want the user can use immediately the password it just filled in the registration.

I tried adding this line in settings.php $conf\['user\_mail\_register\_no\_approval\_required\_notify'\] = FALSE; but the user continues as (not verified).

Thanks!

# Answer
> 1 votes
Jose - Make sure you have "Require e-mail verification when a visitor creates an account" unchecked in your Drupal admin under /admin/config/people/accounts

Also, there seems to be a bug in the services module that doesn't set the password correctly if you send it through the REST service. If you apply this patch, you should be able to set the password and the user should be able to log in right away.

https://drupal.org/files/issues/user\_create-2198005-1.patch

---
Tags: users, services
---


# Question
Title: Filter criteria "Now" doesn't work on submitted data for field:event date
The closest I have found to this is How can I filter a View by the value (or data) of field? which sounded perfect but it didn't work for me.

I need to show a list of values equal to or greater than today's date. For dates in the past, on a value formatted as a date, I use `now` and it works.

I built a view using webform submission data from the latest webform release, which enters a date field as text, for example *2014-05-08*, into the database rather than a timestamp.

I can test it by entering the date into the filter value as *2014-05-08* and it works perfectly, but of course I need today's date to update automatically.

I tried using the token filter (*Y-m-d*) to get the current date, but nothing happens.

I have also installed the *Views PHP* module, but the following code didn't work.

```
$date = date('Y-m-d');
if ($row > value_1 == $date) {
  return TRUE;
}

```

Is there a way to use tokens in the *Configure filter criterion: value* field?

# Answer
I don't really understand the problem. When a date isn't a date anymore and you can use php you can just convert it back to a date.

You even almost use the correct function.

```
$submittedDate = $row>value_1;

$Cdate = date('Y-m-d');
$Sdate = date_format(date_create($submittedDate), 'Y-m-d');

if ($Sdate == $Cdate) {
    return TRUE;
}

```

Shouldn't that do the trick?
> 1 votes

---
Tags: views, webforms
---


# Question
Title: How do I validate form elements via onblur events?
I am trying to validate a form element when it loses focus. But I am having issues calling the validation script. I have tried both:

```
drupal_add_js('(
    function ($)
        {
        $("#edit-field-organization-url").blur(
            function()
                {
                //alert(\'jQuery Exec!\');
                $(this).validate();
                }
        );
        }(jQuery));', 'inline');

```

and

```
$form['field_organization_url']=array(
    '#type' => 'textfield',
    '#title' => t('Website URL'),
    '#weight' => 2,
    '#size' => 60,
    '#maxlength' => 128,
    '#value' => 'www.google.com',
    '#description' => t('Enter website URL.'),
    '#element_validate' => array('hook_node_validate'),
    '#attributes' => array(
        //'onblur'=> '$(this).validate();'),
        //'onblur'=> 'alert(\'jQuery Exec!\');')
    '#required' => TRUE
    );

```

but neither work. I'm guessing this isnt the proper drupal way to call the validation functions.

#########################

UPDATE

#########################

I still cant seem to get it working. The validation code now runs every time the page is loaded and doesnt seem to be tide to the onblur event even though I have it set in the clientside\_ validation module:

> file - template.php:

```
function THEME_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'custom_content_type_node_form':
$form['custom_content_type_node_form']=array(
'#type' => 'textfield',
'#title' => t('Website URL'),
'#value' => 'http://www.google.com',
'#description' => t('Enter website URL.'),
'#element_validate' => array('hook_clientside_validate_url'),
'#required' => TRUE);`

file - custom.module:
`function hook_clientside_validation_rule_alter(&$js_rules, $element, $context) {
switch($context['type']) {
case 'element_validate':
if (in_array('hook_clientside_validate_url', $context['functions'])) {
hook_clientside_validate_url($js_rules, $element);
}
function hook_clientside_validate_url($js_rules, $element) {
//validation code here
}`

```

# Answer
> 3 votes
Drupal doesn't have any client-side validation by default, but you can get that functionality with the Clientside Validation module:

> This module adds clientside validation (aka "Ajax form validation") for all forms and webforms using jquery.validate.

According to the docs it has a "Validate on blur" option, so it should be just what you're looking for.

---
Tags: javascript, forms
---


# Question
Title: Red Herring Error : Class name must be valid object or string
After just having spent two days trying to get to the bottom of a particularly weird bug I thought I'd post up what my question would have been — if I had taken the time to write it — and then post my answer also, just in the hope of helping other people avoid the headache.

> PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522

This was the starting point. I got this error — along with a typically pleasant WSOD — after creating a new install of my site on a localhost. The strange thing about it was that I had almost exactly the same setup working on another machine. The code was served by GitHub and so was identical, the database was a direct dump from the original site, php was configured as expected and versions were only a 0.0.5 out (5.3.15 and 5.3.10), both Drupals were version 7.9 ... everything should be working.

What made this weirder still was the fact the site would work directly after a `drush rr`, however, it would break immediately after a `drush cc all`, or on refresh.

This led my collegue and I traipsing in circles, debugging `common.inc` and `modules.inc` trying to find a clue as to what was going on. What we discovered was that after the reset registry the correct `entity_info` array was built, but after the clear cache, we only got part of the full `entity_info` array.

Investigating further we found rather ridiculously that the following code — taken from module.inc — could not find particular functions in particular module files that we knew to exist.

```
foreach ($list as $module) {
  $include_file = isset($hook_info[$hook]['group']) &&
    module_load_include(
      'inc', $module, $module . '.' . $hook_info[$hook]['group']
    );
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }
}

```

This could only mean that at the point this code was being executed certain files that should have been included by now, weren't. What made this even more baffling was that if we called the following outside of any of the caching code, it returned the correct `entity_info` array.

```
$entity_info = module_invoke_all('entity_info');

```

This meant that there wasn't anything wrong with the files, it just seemed to be the caching system. To cut a rather long story short, because we didn't have anything modifying the core drupal caching system, we decided to resort to the good old trial and error disable all modules and enable one by one. *Great.*

This took some time but we managed to whittle everything down to one bespoke module, which we then trial and errored function by function call. Until we got the culprit:

```
/**
 * Helper function to redirect an actual submit to the ajax handler
 */
function microsites__admin_settings_submit(&$form, &$form_state) {
  return microsites__admin_settings__ajax_button(&$form, &$form_state);
}

```

So I guess my question — apart from being, what can cause `PHP Fatal error: Class name must be a valid object or a string` error — would be what out of the above function could cause such a disastrous error, and in such a weird manner?

# Answer
> 4 votes
For those who have been using PHP a while, it should be obvious what is causing the issue, although what wont be obvious is why Drupal didn't make a song and dance about it.

Basically the cause of the WSOD were the two ampersands denoting call time pass by reference. Something that has been deprecated in PHP for a while. The reason why they were there at all was just a copy and paste typo.

```
return microsites__admin_settings__ajax_button(&$form, &$form_state);

```

The above should have been:

```
return microsites__admin_settings__ajax_button($form, $form_state);

```

With the above change made, everything magically started working again.

Now I might get some people assuming that we just hadn't been keeping track of our errors, but we had as much logging enabled as possible... at no point did either PHP or Drupal complain about the `call time pass by reference`. Instead what Drupal seemed to do — and only after clearing cache I might add — was fail to include other files once it had hit this illegal / deprecated syntax, which then went on to create malformed `entity_info` arrays.

I have since tested this on other files, and all it takes is to add a `call time pass by reference` and it breaks Drupal, at least for all my localhost setups anyway... that is, unless the following has been specified in the php.ini:

```
allow_call_time_pass_reference = On

```

If anyone can ascertain as to why the silence (considering all other PHP errors and warnings are shown), why it broke other files loading, and why the problem only affected when running after a cleared cache, I'd be interested to hear.

Maybe upgrading to 7.22 would fix a few of the above... but in future I'll make sure I double check coherence between my entire php.ini(s) I think; rather than spend a few days trying to bash through a brick wall using only a toothpick.

### update

Just to answer Clive's question, this was the output in the apache error log after I've just tested the same problem again:

```
[Thu Apr 11 11:15:29 2013] [notice] Digest: generating secret for digest authentication ...
[Thu Apr 11 11:15:29 2013] [notice] Digest: done
[Thu Apr 11 11:15:29 2013] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6 configured -- resuming normal operations

```

# Answer
> 2 votes
This is the tip of the iceberg on this problem. (the PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522).

in 7.28, at line 7855, 6 =

```
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type);

```

The issue stems from, for whatever reason, not being able to obtain a $class value from the $type\_info array by executing module\_invoke\_all('entity\_info'). Certainly a call time pass by reference could do it, but that would normally be caught. The actual problem is in /includes/common.inc at 7644.

```
  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
        $entity_info[$name] += array(
          'fieldable' => FALSE,
          'controller class' => 'DrupalDefaultEntityController',
          'static cache' => TRUE,
          'field cache' => TRUE,
          'load hook' => $name . '_load',
          'bundles' => array(),
          'view modes' => array(),
          'entity keys' => array(),
          'translation' => array(),
        );
        $entity_info[$name]['entity keys'] += array(
          'revision' => '',
          'bundle' => '',
        );
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
          $entity_info[$name]['view modes'][$view_mode] += array(
            'custom settings' => FALSE,
          );
        }
        // If no bundle key is provided, assume a single bundle, named after
        // the entity type.
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
        }
        // Prepare entity schema fields SQL info for
        // DrupalEntityControllerInterface::buildQuery().
        if (isset($entity_info[$name]['base table'])) {
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
          if (isset($entity_info[$name]['revision table'])) {
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
          }
        }
      }
      // Let other modules alter the entity info.
      drupal_alter('entity_info', $entity_info);
      cache_set("entity_info:$langcode", $entity_info);
    }
  }

```

Notice that if the condition is true in the if at

```
if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
}

```

then the module\_invoke\_all('entity\_info') is never executed. It just happens that the condition is always met after some other processing is done to create the cache. That means that there is no way to get the entity\_info set up --- in my case there was no way to obtain the 'user' entity info, causing the original error above. I made the 'else' one level higher (took out the 'else {}') for testing, and everything worked as it should to clear the error.

I believe that the real bug is that the checking of cache is less than adequate, and that a check on the existence of the entity\_info about the specific entity being searched for is needed. In fact, it may be justifiable to also search for the element \['controller class'\] for that entity in the entity\_info stored in cache. D

---
Tags: 7, entities, wsod
---


# Question
Title: Migrating existing groups from Commons 2.x to Commons 3
I've just installed Commons 3 on a sandbox server and am curious where to begin migrating groups data over. I realize this is may also apply generic D6 to D7, but is there additional consideration for a Drupal Distribution? What steps should I take to move content and groups from Common 2.x to Commons 3.x?

That is, how can I move existing groups from Commons 2.x into Commons 3.x that will include content types attached to those groups (discussions, postings, events, wikis)?

I know that Activity Streams are different between these versions and we can live with out that, but I'd like to bring over content attached to the appropriate groups and users.

# Answer
> 1 votes
Commons maintainer japerry is in a team that created Commons Migration module exactly for your task.

> Posted by nateswart on March 18, 2013 at 9:46pm
>
> Provide a migration path from Commons 2.x to 3.x

It uses Migrate with Drupal-to-Drupal data migration to get the job done. Sadly, it's still in early development, and according to this feature request not quite finished yet. But at the very least you can see in code what approach original developers use.

# Answer
> 1 votes
When I had that same task, I ended up creating a little custom module based on just migrate\_d2d. The code is obviously specific to our content type structure, but well documented so as to be useful as a template for developing your own custom migration module.

You can find our code here: module migrate\_d2d\_edgeryders. (Unfortunately it does not have its own repo, so you will have to download and install its three files from there manually.)

---
Tags: migrations, 7
---


# Question
Title: Fatal error: Class name must be a valid object or a string in /home/dsmedia/blog/public_html/includes/common.inc on line 7749
I installed a module in drupal called Views Media Browser, that is when I first noticed the issue.

I properly uninstalled the module (unchecked it, uninstalled it, then removed the folder from my sites/all/modules folder). Now when I go to any article content I've created I am welcomed to the above mentioned error.

I checked the file and the location of it mentioned in the error

```
/**
 * Get the entity controller class for an entity type.
 */
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type);
  }
  return $controllers[$entity_type];
}

```

I even compared it to a vanilla version of Drupal and the files are the same.

I noticed that it does not occur with basic pages or any other content type I have. I would prefer not to have to restart the site, so if there is a way to correct this fatal error I would appreciate it.

# Answer
I had a similar issue today (same error message) and I just solved it. It concerns my personal case, but if the description can help anyone : the problem was the fact that I had created a few items with a content type that I deleted since. So these non published items had an invalid class, because the content type was not existing anymore. I found these 3 items in the list of content with a blank space instead of the content type name. Deleting these 3 items, and then extracting/importing the database again to the customer made it work.

The stange thing is that my version of the site was still working since I deleted the content type, so I couldn't understand why suddenly this problem when migrating the site.
> 0 votes

# Answer
This issue has been raised and closed (without repair) a huge number of times (more than 50 that I can see). It is, admittedly, a tough one to find. I have entered the issue. I have tracked down the actual cause, but the intricacies of the cache are a bit beyond me.

Clearing the cache could help here. Sadly, you can't always get there, largely because drush cc will also blow up when this error is occurring. So will anything having to do with accessing a user (in my case). . Requiring a user to clear the cache every time this occurs is improper by its nature - you can't have a user do a workaround as a normal course of business.

This is the tip of the iceberg on this problem. (the PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522).

\[\[\[\[in 7.28, at line 7855, 6 = \]\]\]\]

$class = $type\_info\['controller class'\]; $controllers\[$entity\_type\] = new $class($entity\_type);

The symptom appears because the search for the element \['controller class'\] is presumed to be successful. It is not, and no secondary message (such as in a try / catch or an actual test here) is generated.

The issue stems from, for whatever reason, not being able to obtain a $class value from the $type\_info array by executing module\_invoke\_all('entity\_info'). Certainly a call time pass by reference could do it, but that would normally be caught. The actual problem is in /includes/common.inc at 7644.

```
  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
        $entity_info[$name] += array(
          'fieldable' => FALSE,
          'controller class' => 'DrupalDefaultEntityController',
          'static cache' => TRUE,
          'field cache' => TRUE,
          'load hook' => $name . '_load',
          'bundles' => array(),
          'view modes' => array(),
          'entity keys' => array(),
          'translation' => array(),
        );
        $entity_info[$name]['entity keys'] += array(
          'revision' => '',
          'bundle' => '',
        );
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
          $entity_info[$name]['view modes'][$view_mode] += array(
            'custom settings' => FALSE,
          );
        }
        // If no bundle key is provided, assume a single bundle, named after
        // the entity type.
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
        }
        // Prepare entity schema fields SQL info for
        // DrupalEntityControllerInterface::buildQuery().
        if (isset($entity_info[$name]['base table'])) {
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
          if (isset($entity_info[$name]['revision table'])) {
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
          }
        }
      }
      // Let other modules alter the entity info.
      drupal_alter('entity_info', $entity_info);
      cache_set("entity_info:$langcode", $entity_info);
    }
  }

```

Notice that if the condition is true in the if at

if ($cache = cache\_get("entity\_info:$langcode")) { $entity\_info = $cache-\>data; }

then the module\_invoke\_all('entity\_info') is never executed. It just happens that the condition is always met after some other processing is done to create the cache. That means that there is no way to get the entity\_info set up --- in my case there was no way to obtain the 'user' entity info, causing the original error above. I made the 'else' one level higher (took out the 'else {}') for testing, and everything worked as it should to clear the error.

I believe that the real bug is that the checking of cache is less than adequate, and that a check on the existence of the entity\_info about the specific entity being searched for is needed. In fact, it may be justifiable to also search for the element \['controller class'\] for that entity in the entity\_info stored in cache. D
> -1 votes

---
Tags: 7, entities
---


# Question
Title: Template conditional based on a list field
I have a 'List (text)' field set up with five options displayed as a series of checkboxes.

I would like the last of these checkboxes to control the visibility of a button in the node template.

```
<?php if($node->field_the_checkbox_field['und'][0]['value'] == 'key_of_checkbox'): ?>
    // do stuff
<?php endif; ?>

```

The problem with the above is that it only works when this checkbox is the only one selected, otherwise it is no longer the '\[0\]' result.

How could I go about checking all of the potential five checkboxes for my result?

Thanks!

**EDIT**

I thought I'd found a horribly verbose workaround by checking every offset one by one like so:

```
<?php if($node->field_the_checkbox_field['und'][0]['value'] == 'key_of_checkbox'
    || $node->field_the_checkbox_field['und'][1]['value'] == 'key_of_checkbox'
    || $node->field_the_checkbox_field['und'][2]['value'] == 'key_of_checkbox'): ?>
        // do stuff
<?php endif; ?>

```

etc... but, now I get an 'undefined offset' error for each offset that doesn't exist, ie. not all of the boxes will ever be checked, and so there are never usually five results, meaning that when only two of these checkboxes are checked offsets 2 - 4 don't exist. PHP doesn't like that, apparently.

I'm wondering if my problem here is that I should be using five boolean checkboxes, which at least will always return a result one way or another. That seemed messy when I was planning this out, but now it's looking ever more inviting!

**EDIT 2**

Since I'm short on time, I decided to go with my thoughts above and base my conditionals on single points of data which can either return me a 'true' or 'false' status. My PHP (as you can probably see above) is crappy to say the least - far too crappy to work out how to get around this one. I'd be interested if anyone has any ideas regarding this though!

Thanks for reading.

**EXTRA EDITS** for clarity and grammar

# Answer
> 0 votes
My php isn't the best, but I think this should work...

You could try using a foreach loop, and using a condition similar to this:

```
<?php foreach ($node->field_the_checkbox_field['und'] as $thisfield) {
    if($thisfield['value'] == 'key_of_checkbox'):
   // do stuff
} ?>

```

---
Tags: 7, entities, theming
---


title: How to assign users to a group

text:
# Question
Title: How to assign users to a group
How do I assign users to a group in Drupal 7? Basically I wanted to have following groups in my website.

1. Administrators
2. Content Writer and Publisher
3. Registered users

I wanted to assign all of the newly registered users to "Registered users" group automatically and I as a member of administrator should be able to assign some trusted users into "Content Writer and Publisher" group.

Each of these groups will have different-2 permissions as expected.

# Answer
> 4 votes
From a permission point of view, (instead of groups) these are called "roles" in Drupal. (From a content-user-access point of view there is the Organic groups module, but that's another story.)

You can administer roles at admin/people/permissions/roles. You can mass assign users to roles at admin/people (Update options - Add a role to selected users).

All registered users automatically have a role called "authenticated user", so there is no need to duplicate that functionality.

For more info check out "Managing access control with permissions and user roles" at https://drupal.org/node/22275

# Answer
> 1 votes
Check out Registration Role:

From the module's project page:

> Registration role lets an administrator select a role to automatically assign to new users. The selected role will be assigned to new registrants.

It assigns a selected role on signup of a new user.

# Answer
> 0 votes
I use - Role field, Rules. Create field role and assign this role from Rules module.

---
Tags: 7, users
---


# Question
Title: How can one determine if a view is empty using views_embed_view()?
I need to add a header to the page markup if a call to `views_embed_view()` retrieved any content, and hide it if not. Unfortunately, an empty view produces this markup:

```
<div class="view view-related-content view-id-related_content view-display-id-block view-dom-id-a62e1bda4cd2427adcbfba7ad95dec6e">

</div>

```

(I've left the spacing in to be as accurate as possible).

The view is set to hide results when the argument for the (only) contextual filter is not present.

How can I determine whether the view actually has any results, without incurring any extra DB overhead?

I'm looking to do this just with API functions as overriding templates for something so trivial is not palatable. I'm also not looking for any hacks (e.g. measuring the length of the return string and hiding the header based on that).

# Answer
views\_embed\_view() does something along the lines of this:

```
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

```

and views\_get\_view\_result() does something along the lines of this:

```
function views_get_view_result($name, $display_id = NULL) {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }
    if (is_string($display_id)) {
      $view->set_display($display_id);
    }
    else {
      $view->init_display();
    }
    $view->pre_execute();
    $view->execute();
    return $view->result;
  }
  else {
    return array();
  }
}

```

so you could combine them to make your own custom module embed like this:

```
function YOURMODULE_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }
    $view->set_display($display_id);
    $view->pre_execute();
    $view->execute();

    if (!empty($view->result[0])) {
      return $view->preview();
    } else {
      return FALSE;
    }
  }
  else {
    return FALSE;
  }
}

```

(D6 code above, D7 is quite similar)
> 7 votes

# Answer
You could use views\_get\_view\_result() which returns an empty array if the view has no result to display.
> 10 votes

# Answer
I had the exact same problem. This is what i did -

```
$view = views_get_view('view_name');
$print_view = $view->preview('display_id', array('argument1','argument2'));
if(!empty($view->result)) {
  print $print_view;
}

```

Hope that helps somebody.
> 5 votes

# Answer
With help from the posts by Jimajamma and bsfoo116, here's the straight up short answer:

```
$checkempty = views_get_view_result('my_view_name', 'my_display_name');
if (!empty($checkempty)) print views_embed_view('my_view_name', 'my_display_name');

```
> 2 votes

# Answer
A lighter weight solution is to simply search the output for the text 'views-rows'. If there are no results, this text generally wont be rendered (though of course it will vary based on your specific configurations).

I was able to successfully use this in one of my projects to make sure a block got hidden appropriately.

```
$block['content'] = views_embed_view('volumes', 'default', $group_id);

if(strpos($block['content'], 'views-row') === false){
    $block['content'] = false;
}

```

Obviously the other solutions listed here are more complete, but this is a quick and straightforward way to do it.
> 1 votes

---
Tags: views
---


title: How does Views contextual filters work?

text:
# Question
Title: How does Views contextual filters work?
I'm trying to wrap my head around contextual filters again! I used it a while back but I just got totally stumped again. Here's what I'm trying to do:

1. Generate a cloned content node page with taxonomy terms inserted into this cloned page.

ex.: EXAMPLE.com/white-shoes/blue

When a user reaches the /white-shoes page it will show the original node page geared toward the white color. Now if the user lands on /white-shoes/blue it will show the same node page, but this time all of the body content will be rewritten replacing the white color with blue color.

In Views I would have to create a Page display with the path of: %/%

Now I would create a contextual filter to retrieve the nid. I add Content: nid as a contextual filter. I pick **PROVIDE A DEFAULT VALUE** and I put in this PHP code:

> $x = drupal\_lookup\_path('source', arg(0));
>
> $y = explode('/', $x);
>
> return $y;

That PHP code basically converts the /white-shoes part of the URL into a NID. But it doesnt work. I tested the code via **drush ev** via the terminal and I indeed get a returned result, so i know it works.

I do the same for the taxonomy term name and add a contextual filter for that aswell. This time I pick **PROVIDE A DEFAULT VALUE** and select **RAW VALUE FROM URL** and select the 2nd argument.

As you can see when I input a PREVIEW VALUE for the contextual filter: AAA/BBB/CCC . My default value gets ignored. It's supposed to be grabbing the 2nd argument, but it's getting the 1st only. Look at the SQL statement WHERE and you'll see it's getting AAA when it should be BBB.

So the question is what am I doing wrong or is there a better solution to what I want to accomplish?

# Answer
> 2 votes
Here's a video and its related article that'll explain you how to use them, the example uses Pets (Dogs, Cats) which may be a simple enough example to help understand how to use Views Contextual Filters.

**VIDEO:** https://www.youtube.com/watch?v=lJFMTDuaxy8 (YouTube video short-url: lJFMTDuaxy8)

**ARTICLE:** http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

# Answer
> 5 votes
Contextual Filter is used to filter ,output of the view by URL arguments, also u can pass the arguments manually in this format:

```
<?php print views_embed_view($name,$display_id,$arg1,$arg2,$arg3); ?>

```

where "$name" is the name of your view (ex. 'example\_view') and '$display\_id' is the display type of your view (ex. 'default') and "$arg1,$arg2,$arg3" are arguments just like in URL.

**URL arguments has the following structure:**

http://example.com/arg\_1/arg\_2/arg\_3 (arg\_2 has the path component 2 (in view setting page)).

**When the filter value is not availabe:**

it means drupal can't find any filter.

**Provide default value:**

when the filter value is not available you can use this option to to creat a filter for views output, this filter can be PHP code (if PHP filter module enabled) or it can get it's value from the URL arguments--\> (Raw value from url). The Exception textbox allows you to cheat the value and display all results.

**When the filter value is available**

in this case you do a validation as your needs and some other options, when drupal can find the filter value.

---
Tags: 7, commerce, views
---


title: One view for multiple pages?

text:
# Question
Title: One view for multiple pages?
I have nodes from a content type that are put in a paged view (show 1/page) You can see it here: http://stage.e-clear.eu/en/chemicali%C3%ABn http://stage.e-clear.eu/en/Energie As you see this are multiple views for multiple pages (in example chemicals and energy)

I want a view that creates multiple pages like a published filter but invisible with nice url's like /energy.

# Answer
I know what you're trying to do with Views, and it's easier than you think once you get comfortable with Views Contextual Filters.

Check out this video (or the text version article) that clearly walks through how to use Drupal Views Contextual Filters. The linked examples use Pets (Dogs, Cats) as sample data, so you'll see how to filter Cats versus Dogs quickly.

**VIDEO:** https://www.youtube.com/watch?v=lJFMTDuaxy8 (YouTube video short-url: lJFMTDuaxy8)

**ARTICLE:** http://www.metaltoad.com/blog/using-drupal-contextual-filters-views
> 0 votes

---
Tags: views, paging
---


title: Tabular data representation

text:
# Question
Title: Tabular data representation
I am building a demo site, trying to learn commerce kickstarter. I figured out a lot of it but i wanted to add something more to the items.

If you click this link : http://www.sigmaphoto.com/product/sd15-digital-slr-camera I don't own that or promote that site , i found it on drupale commerce kickstarter showcase. My question is how can i create tabs that are like under the pictures. OVERVIEW | TECH SPEC | ACCESSORIES

Do you need to create a view or is there a field that you can add so you can input the data in the content type ?

# Answer
> 0 votes
Yes, there is actually a few modules that will allow you to get tabs in your content easily. The one I use is **Quicktabs**, listed below along with some alternative modules.

1. **Quicktabs** (module) - https://drupal.org/project/quicktabs
2. **Field Group** (module) - https://drupal.org/project/field\_group (has tabs support)
3. **jQuery Tabs Field** (module) - https://drupal.org/project/field\_jquery\_tabs

---
Tags: entities, commerce
---


# Question
Title: Fresh install with minimal: missing manage display even with field_ui turned on
I just installed a fresh copy of Drupal 7 and chose the minimal install option. I enabled `field_ui` and I still do not see the **manage display** tab on content pages. However it does show up when you goto the content type directly. Did i forget to click somewhere?

# Answer
> 0 votes
For displaying **Manage Display** tab on content page you have to install Display Suite module.

On drupal core no such module or configuration that display this tab on content page. So you didn't forget anything for this.

---
Tags: 7, entities
---


title: Updates break jquery modules

text:
# Question
Title: Updates break jquery modules
I could need some help! (Newbie) After updating a couple of modules on my local site, the jquery modules are behaving really weird or stopped working at all (Masonry, Chosen and Sidr). Masonry and Chosen don't work at all, Sidr just works on those pages where Masonry isn't on. Infinite Scroll stopped working, too and is replaced by the regular pagination. There are no error messages displayed or in the drupal report. What should I do now? (the site is running Drupal 7.28 on Acquia Dev Desktop php 5.2.38)

# Answer
1. Caches may be stale. Clear and re-test. Even disable your JS aggregation/minify, then have Drupal regenerate the aggregated JS (after testing with it off to see if that fixed the issue).
2. If you also use the `jquery_update` module, you may need to update your jQuery library.
3. Sometimes replacing the modules with their DEV versions help fix the issue, because sometimes there's small bugs that get fixed in DEV first before a new stable update is tagged and released.
> 0 votes

# Answer
It could be that you updated `jQuery Update`, and it provided a version of jQuery UI that was too new for those modules. If you have `jQuery Update` installed, then try switching the versions of jQuery UI and see if one fixes them.

Also, clear all the caches whenever you switch.
> 0 votes

---
Tags: javascript, updating
---


# Question
Title: Is it possible to download sandbox projects with Drush?
Normally, one can download a module from drupal.org like this:

`drush dl views`

However, this doesn't work for sandbox projects. Is there an easy way to download them or I am stuck with `git clone`?

# Answer
I do believe you're stuck with git for this one. Drush requires the use of a module name, even when fetching with git (`drush dl --package-handler=git_drupalorg`), and sandbox projects don't have module names.

Drush also requires you to download a release of a module. Sandbox projects have no releases. This may also just be by design, since using sandbox modules can be dangerous, and is made difficult on purpose.

You could slightly automate it with a git alias. You could set up something like:

```
git dl-sb username/number project_name

```

This would just do `git clone http://git.drupal.org/sandbox/username/number.git project_name`

You could also write a drush command that would do the same thing, though it would be a weird drush command...
> 18 votes

# Answer
It's possible to download sandbox project with drush using make file.

Here is example.make file:

```
core = 7.x
api = 2
; Sandbox module
projects[range_field][type] = module
projects[range_field][download][type] = git
projects[range_field][download][branch] = "7.x-1.x"
projects[range_field][download][url] = http://git.drupal.org/sandbox/Taran2L/1848632.git
projects[range_field][download][revision] = a1cc04da3c1dd957e6808b7e6a381c5970904863

```

Then you can execute it via:

```
drush make --no-core example.make # optional options are: -y --working-copy --no-gitinfofile --verbose

```
> 20 votes

# Answer
The page Jonathan Sibley is refering to (http://drupal.org/node/1576296) says something like:

1. Go to the project page;
2. Follow "Repository viewer" link;
3. Under "Heads" click the "Tree" link of the branch of your likings;
4. Click the "Snapshot" link to download the sandbox module.
> 1 votes

---
Tags: drush
---


# Question
Title: Ideas for Realistic Sample Content for Demo Site
I have a couple of drupal interviews coming up. Not that this is an excuse, but it is my excuse-- Since I have worked on sites for other companies, I don't have my own body of work to display, meaning I don't have a portfolio of sites that I have created from beginning to end for specific clients.

In preparation for these interviews,I have created four sites, but what is killing me is the content. I set the sites up and use devel generate to get dummy content in, so I can see how things will look, but my recruiters are saying, and I agree, I need realistic text/content. This part is killing me, trying to make so much stuff up.

I have gone to sites to basically "borrow" and modify their content.

I want to see if anyone else has a better method for adding realistic content to their demo drupal sites.

Any suggestion would be greatly appreciated.

# Answer
> 0 votes
You can take content from other sites on the website, just make sure you are taking content you are legally allowed to use so you aren't breaching copyright.

I would recommend using content from Wikipedia to make your pages as you can an extreme amount of information there to make professional looking content.

For information on the legalities of using Wikipedia content, see Wikipedia:Reusing Wikipedia content.

# Answer
> 1 votes
Realistic - if you mean word and letter distribution, at least - filler text in the industry is called Lorem ipsum.

> In publishing and graphic design, lorem ipsum is a placeholder text commonly used to demonstrate the graphic elements of a document or visual presentation. By replacing the distraction of meaningful content with filler text of scrambled Latin it allows viewers to focus on graphical elements such as font, typography, and layout.

There is a Drupal 8 module for it, called simply ipsum, based on now-unmaintained but basically still working Drupal Ipsum.

Also, good old Devel module has a Generate submodule with it's own lorem ipsum style generator:

> Accelerate development of your site or module by quickly generating nodes, comments, terms, users, and more.

# Never use actual content from 3rd party sites

without proper permission and proper disclaimer. There are 2 major legal reasons:

1. It is good old copyright violation, just as if you would take a song by someone else, put it in your musical and never told anyone...
2. If you will get a job or commission by pretending something is your work, when it isn't, even if it was a negligible part of work, in many countries it will count as fraud. Up to 8 years in prison where I live.

---
Tags: nodes
---


# Question
Title: Post comment permission by content type and role
I want to only allow users of a specific role to be able to comment on a specific content type. The only current solution for this is using the "Comment Permissions" module which unfortunately is only available for Drupal 6 and hasn't been updated for over a year. I have seen some people saying that it's possible to do this by writing custom code however i haven't been able to find any examples of this. Does anyone here know how this could be done or at least point me in the right direction? I'm not good at php though i have some programming experience.

I was thinking that it would also be okay if i could allow users of a specific role to comment on nodes/content type where commenting has been closed if achieving it that way is simpler.

Any help is greatly appreciated.

# Answer
> 4 votes
These days there is a D7 version of Comment Permissions. Here is a quote about it (from the module's project page):

> ... enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

---
Tags: 7, users, comments
---


# Question
Title: Hide and Reveal Sidebar Blocks in Drupal 7?
I am working on a 1920px-wide site that will be displayed on HDTVs internally at an office. I'd like to place text and other info into (ideally) sidebar blocks, but I'd like for those blocks to be hidden when the page loads. Then, when someone clicks a block's title, that block alone would expand, displaying its content over the primary content area. I have attached an image to illustrate what I mean.

Does anyone here know of a module that can accommodate this type of functionality? If not, any recommendations on how to achieve this would be most appreciated. The sidebar content does not necessarily have to be in blocks.

# Answer
> 1 votes
In the themes .info file you can add a line like this

"scripts\[\] = myscript.js". This is eplained in the drupal theming guide -\> http://drupal.org/node/171205.

Drupal will then load your js file and automatically insert jquery too.

This is the code that you need to put in the js file. Be aware that every region has a div with the class name. Example "region-footer". So thats how you can target them easilly. Make sure you set a width in you css file for the element.otherwise jquery cannot toggle the width.

```
(function($) {
    $(document).ready(function() {
        $('.region-footer .block h2').click(function() {
            $(this).parent().children('.block-inner').animate({
                width: 'toggle'
            },5000, 'swing');
        });
    });
})(jQuery);

```

You could also animate/toggle the margin instead of the width. If you do that remember to declare the negative margin for the element in your css file.

Do not forget to clear the cache after altering your themes .info file.

Tip : You could add a nice animation with http://gsgd.co.uk/sandbox/jquery/easing/

# Answer
> 0 votes
I have made a little demo for you.

http://jsfiddle.net/UV2hk/

just include this in a Jquery wrapper through the themes `.info` file.

Here it is.

```
jQuery('#label').click(function(){
    jQuery('#content').animate({
        width: 'toggle'
    })
});

```

# Answer
> 0 votes
Here's a sandbox module that might help:

https://drupal.org/sandbox/mathieso/2264649

It lets users toggle (show/hide) a sidebar region, with all of its blocks.

Kieran

---
Tags: blocks
---


# Question
Title: Views AJAX Submit is removing my custom classes
I have custom jQuery that I've added to views filters to my ajax view. When a user selects certain criteria a slideDown and addClass event is triggered and a new set of filters is shown. You can view it here:

https://www.feedingmatters.org/helpful-books

When I click submit the classes that are added to my elements are removed by Drupal. This causes the elements to display: none and now the users can no longer see their filter trail. How can I either stop Drupal from clearing my addClass? The filters need to remain visible so long as the correct criteria are selected.

Note: I tried views dependent filters but it doesn't work as needed.

# Answer
> 1 votes
I struggled with this recently in this question

The answer is to wrap your jQuery in a Drupal Behaviour so that the classes are not removed on every ajax request. Because your current jQuery is probably only run on the first page load.

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

        // Put your jQuery Code Here

  }
};
})(jQuery);

```

---
Tags: 7, ajax, javascript, views
---


# Question
Title: Hook_Form_Alter Edit Existing Field Type
I am using hook\_form\_alter in template.php to add datepicker to a field on an exposed view filter.

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == "views_exposed_form"){
    $form['data_2_op'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}

```

But all it is doing is adding another field into the form, rather than editing the field I have declared. Is there a way I can just add #type \> 'date\_popup' to an existing field?

EDIT:

Results after using...

```
drupal_set_message($form_id);  // print form ID to messages
  drupal_set_message(print_r($form, TRUE));  // print array to messages

views_exposed_form
Array (
  [#info] => Array (
    [filter-combine] => Array (
      [operator] => combine_op
      [value] => combine
      [label] => Search Event ID
      [description] =>
    )
[filter-data_2] => Array (
  [operator] => data_2_op
  [value] => data_2
  [label] => Choose Date [description] =>
  )
[filter-data] => Array (
  [value] => data
  [label] => Data field
  [description] => )
  [filter-data_1] => Array (
    [value] => data_1
    [label] => Data field
    [description] =>
    )
  )
[combine] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )
[data_2] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )

```

# Answer
> 1 votes
hook\_form\_alter work only with module implementation. So you have to use it in any module not in template.php

Use the above statement in module like

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == "views_exposed_form"){
    $form['data_2'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}

```

---
Tags: forms
---


# Question
Title: i'm running Acquia Desktop, what exactly triggers the install.php page?
this keeps happening by mistake in various scenarios but once such scenario is this:

I'm doing some in-depth tutorials and required to drop all tables then do a massive SQL injection via PHPMyAdmin. And then additionally, replace the entire file system at the beginning of some lessons.

but instead of a populate website i get presented w/ the installer screen and don't know why. several times now i've had to start completely over.

what exactly triggers the install page? and considering i have a populated DB and file system, what steps do i need to take, or what should i be looking at to get he site to load?

# Answer
I found it, at the very bottom of the settings file, if i put the code below back then the installer will NOT launch, which is what i want

```
//<DDSETTINGS>
// Please don't edit anything between <DDSETTINGS> tags.
// This section is autogenerated by Acquia Dev Desktop.
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) &&     file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .    '/loc_ravianatwo_local.inc'))
  require($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .        '/loc_ravianatwo_local.inc');
//</DDSETTINGS>

```
> 0 votes

---
Tags: installation, acquia-dev-desktop
---


# Question
Title: How to add custom theme to module block on Drupal 7?
I saw lot of questions and answers on this but I can't find solution. I need to show last posts trough tpl file and I can't figure how to do it. Also I don't know what to put in my tpl file.

Edit!: This is my hook\_block\_view () function and if I send data at the end of it like theme('item\_list', ... it works perfectly. But I need to send it to my custom tpl file and when I do that it won't properly display list. I think that there is problem in .tpl file.

```
<?php
function last_5_user_posts_block_view($delta = '') {
$block = array();

switch ($delta) {
case 'last_5_user_posts':

  // Capture the image file path and form into HTML with attributes
$image_file = file_load(variable_get('last_5_user_post_image', ''));
$image_path = '';

if (isset($image_file->uri)) {
$image_path = $image_file->uri;
}

$image = theme_image(array(
    'path' => ($image_path),
    'alt' => t('Image description here.'),
    'attributes' => array('class' => 'class_name'),
    'width' => '12',
    'height' => '12',
    ));

  $block['subject'] = t('My last posts');
  if (user_access('access content')) {
    // Use our custom function to retrieve data.
    $result = last_5_user_posts_contents();
    // Array to contain items for the block to render.
    $items = array();
    // Iterate over the resultset and format as links.
    foreach ($result as $node) {
      $items[] = array(
        'data' => $image.l($node->title, 'node/' . $node->nid),
      );
    }
   // If there is no nodes
    if (empty($items)) {
      $block['content'] = t('No posts available.');
    }
    else {
      // Pass data through theme function.
   //   $block['content'] = theme('last_5_user_posts_output', array(
   //       'items' => $items));
        $govno = 'Govno!';
        $listitems = array('items' => $items);
      $block['content'] = theme('last_5_user_posts_output', array(
          'items' => $items));
    }
  }

  return $block;

}

}

```

And my .tpl file for now contain just:

```
 <div class="field-items"<?php print $content_attributes; ?>>
 <ol style="list-style: circle">
 <?php foreach ($items as $delta => $item): ?>
 <li>
 <div class="field-item" style="color: red;"><?php print render($item); ?></div>
 </li>
 <?php endforeach; ?>
 </ol>
</div>

```

If I create array:

```
$test[1] = 'Test!';
$test[2] = 'Test2!';
$test[3] = 'Test3!';

```

And send it trough $block\['content'\] like this

```
$block['content'] = theme('last_5_user_posts_output', array(
          'test' => $test));

```

It works pefectly! But for $items it won't work. How to optimize $items to get it in .tlp??

# Answer
Resolved! In

```
function last_5_user_posts_block_view($delta = '') {

```

I changed $items in foreach to

```
foreach ($result as $node) {
        $items[] = $image.l($node->title, 'node/' . $node->nid);
    }

```

It is simple and I hope that I will help someone with this solution.
> 0 votes

# Answer
Was too long for a comment...

If all you want is the last 5 posts of the current user - create a view:

* choose content type
* Create a limit under Pager (presumably of 5)
* advanced - relationship author
* filter by currently logged in user
* sort by post date descending

This will create a view (be it a page or block) that shows the last 5 posts of whatever content you want for the currently logged in user. If you want to include it as a block, create as a block, and in the block configuration for that view (under structure/blocks), you can decide where on the page and for which pages you want the block to appear.

You can decide which content types are included via the filter, and decide the layout.
> 0 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Printing a drupal 7 user field into a link
Ok so my goal here is to allow users to link there social media profiles onto their user pages. So i tried to print the field within an href statement so it would come out as a link. For example if the value for the field link is http://www.google.com, then it should output the text link with a link to google when clicked.

But it doesnt, it instead outputs the value for the field\_link and links it to

Heres what i attempted at:

```
<html>
<a href="<?php print render($user_profile['field_link']); ?>">Link</a>
</html>

```

Any help is appreciated!

Edit: Ok so this is what it outputs:

```
<a href=" <div class="field field-name-field-link field-type-text field-label-hidden><div class="field-items"><div class="field-item even">http://www.google.com</div></div>  </div> ">

```

But i only want the web address Please Help!!

# Answer
> 1 votes
Use the Link field Module:

> The link module can be count to the top 50 modules in Drupal installations and provides a standard custom content field for links. With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

Or better, yet do a search for drupal social media for a number of different modules to do exactly this.

---
Tags: entities, navigation, theming
---


# Question
Title: Cannot get rules component to fire on Commerce Completing the checkout process
I have a baffling situation. I created a nice little rules component that retrieves a list, using VBO, of published Drupal Commerce Product Display nodes with referenced product stock of zero or less. And then loops through that list unpublishing each node. This is how I built it - https://drupal.org/node/1345216#comment-8306801

This component works as expected when executing it by itself or when placing it in a rule with the "After updating an existing commerce product" and/or "After updating existing content" events. I cannot get it to run when attaching it to a "Completing the checkout process" event.

Any ideas? Is it a permissions issue, as in customer cannot run the component or access the VBO list?

Is there another event related to a customer completing an order that might work better?

# Answer
> 0 votes
It's possible the user doesn't have access to execute the rules component. You can check the permission in admin user permissions or on the rule component edit page.

Keep in mind the rules component will need to be attached to a reaction rule to fire on the checkout complete event.

Other than that, if the component can process the passed `$commerce_order` parameter (passed to checkout complete), then it should be ok.

---
Tags: commerce, rules
---


title: Can I import "id" into "uid"?

text:
# Question
Title: Can I import "id" into "uid"?
I'm trying to import over 5000 users into drupal by using Feeds module. Can I import user "id" into "uid"? If so, how can I do that? I saw the GUID mapping target, but that is not "uid". Thanks.

# Answer
> 1 votes
The user ID field on Drupal is auto-incremented, so you don't want to import your ID values into that field. It's much better to add an *original\_id* field to retain the legacy user IDs.

---
Tags: feeds
---


# Question
Title: Create exposed filter for Views PHP value
I have created a views field using the Views PHP module. This field converts a text date string into a date stamp, and now I need to create an exposed filter for organising the rows.

I add a filter "Global: Combine fields filter", and under "CHOOSE FIELDS TO COMBINE FOR FILTERING" I select Global:PHP to select my field, but the filter doesn't work, I just get the following error...

```
SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax
to use near ') LIKE '2014-01-03') ))) subquery' at line 4

```

I need to create an exposed grouped filter for "Todays events", "Tomorrows events", "upcoming events". Is it possible to create a filter for a field rendered by views PHP?

I have searched loads of similar questions, but they have all gone unanswered. Can anyone help?

# Answer
If you are using Views PHP, then you are using it's alpha or development version. Alpha tests means that maintainer *expects* there to be bugs and want you to report them in issue queue. Development version *almost certainly* have issues, that's the nature of ongoing development.

Having that said, you shouldn't attempt to use exposed filters on fields that are not in database, and cannot be readily joined and used in SQL `WHERE` with your data. Unless, of course, module that provides it already implemented it properly, and it appears it is not the case here. So your options are:

1. Forget Views PHP for dates, and use regular Date to get date fields attached to your entities, and Date views submodule for views exposed filters, or
2. Post a bugreport and wait for it to be fixed. Just don't really expect it to happen, as module currently lacks manpower and is seeking co-maintainers.
> 2 votes

---
Tags: views
---


# Question
Title: HTTP request status fails, but update checking works manually
I have a problem with my Drupal 7 (multi-site) installation on a root-server. The HTTP request status shows "failed" on the status page. However, I am able to check for updates manually when logged in without a problem, so Drupal actually is allowed to access other sites.

I am having problems with automatic update-checks via cron though. Sometimes they work, sometimes they work only partially. This results in an error-report being sent sometimes via email, which is quite annoying since I only want this for security updates.

Does anyone know how to solve this? We do have a root-server, however I'm not the admin and other non-drupal sites run on it too, so I can't just play around with server-settings, I would have to request changes (I can see phpInfo() though, if that helps).

The weird thing is that updates do work manually, and at least partially when checked via cron (I also disabled any external cron-job, so it's only triggered via poor-man's-cron). Could it be a Drupal core problem after all, maybe related to this: https://drupal.org/node/965078?

-- Drupal 7.27, all modules up-to-date

# Answer
This is most likely caused by an old issue, a time-out of 5 seconds which is easily exceeded when checking for updates via poor-man's cron on sites with more than a few modules. See this issue.

Easiest solution is probably to use real cron jobs if possible to avoid this altogether, although there are other suggestions on the linked site. Drupal 7.28 finally increased the limit to 30 seconds, in many cases this might suffice. However it may lead to a page load slow-down, so imho it's better to avoid poor man's cron.
> 0 votes

---
Tags: updating, cron
---


title: How to render links to youtube as video

text:
# Question
Title: How to render links to youtube as video
I'd like to know, how could I render links to video sites like youtube and vimeo as a video, the way Facebook does when a user simply pastes a link.

The other modules or solutions I've found involved embedding videos as a field requiring users to go through a process like the one from Embeded Media Field module does. The closest one is the Video Filter module, but it still more complicated that Facebook.

I'd like this feature over because I'm implementing this for a forum and I'd like to make it as simple and familiar (since everyone uses Facebook) as possible.

# Answer
I guess the simplest solution would be a normal textfield with a youtube-specific formatter. A formatter is some code that takes the value of a certain field and uses it to generate a chunk of html, displaying the field on your page the way you want. The downside of this solution is that it will add a separate field to your form.

A quick search found two sandboxes with youtube field formatters:

Unfortunately I could't find an oficially released, stable module.

If you want complete control over your formatter, here's a tutorial how to create your own: Creating Custom Formatters with the Field API. In the comments, some commenters even say it helped them create a youtube field formatter.

**\[Update\]**

I just noticed the Googtube module, it seems to be exactly what you're looking for: like Video Filter module, but parsing regular YouTube URL's as embedded video's.
> 1 votes

# Answer
Regarding Youtube, I just used the iframe link that Youtube provided and defined my own size for the frame:

```
<div><iframe width="220" height="165" src="//www.youtube.com/embed/XgYu7-DQjDQ" frameborder="0" allowfullscreen></iframe></div>

```

This displayed as a video frame right there on the page, which could be viewed in the thumbnail size and in full screen view as well as on Youtube, since the frame contains the link.

Edit: see the example at http://www.crossroadpublishing.com/crossroad/title/call-to-serve The only thing is that my above code was sized for a front page thumbnail size space.

I hope this helps. Gábor
> 0 votes

---
Tags: wysiwyg, files
---


# Question
Title: Slow migration process when migrating nested field collections
I'm migrating a site with something like 2000 nodes each having some field collections with other field collections nested in them. Basically, example node looks like this:

```
              level 1                 level 2
node -> field collection[0] ->  field collection[0] -> fields
     |                      |-> field collection[1] -> fields
     |                      |-> field collection[2] -> fields
     |
     -> field collection[1] -> field collection[0] -> fields
                            |-> field collection[1] -> fields
                            |-> field collection[2] -> fields
                            |-> field collection[3] -> fields
                            |-> field collection[4] -> fields

```

So, each node can have one or more `level 1` field collections and each `level 1` collection can have one or more `level 2` collections.

My migration procedure was to first migrate `nodes`, then `level 1` collections and now I'm migrating `level 2` collections. Everything seems to work fine but when I got to `level 2` import, the migration process slowed down to a crawl: close to **one field collection entity per second!**

This is insane! I've checked the queries that are being run during migration and it turned out that each migrated collection triggers a query that looks like this:

```
INSERT INTO field_data_field_level_2 (
    entity_type, entity_id, revision_id, bundle, delta, language,
    field_level_2_value, field_level_2_revision_id)
VALUES
    ('field_collection_item', '1486', '1486', 'field_level_1', '0', 'und', '3626', '3626'),
    ('field_collection_item', '1486', '1486', 'field_level_1', '1', 'und', '3627', '3627'),
    ('field_collection_item', '1486', '1486', 'field_level_1', '2', 'und', '3628', '3628'),
    ('field_collection_item', '1486', '1486', 'field_level_1', '3', 'und', '3629', '3629'),
    ...
    ...

```

The list goes on and on up to hundreds of rows! And it is increasing with each imported field collection. This is insane. How to optimize that?

The data is imported from other database, so `map_joinable` is set to `false` \- could this be the reason? But why? It looks like for each import some rows are deleted and then saved again.

I've ran the import process with `--instrument` switch and got these results:

```
Name                Cum (bytes)  Count  Avg (bytes)
 destination import  51215952     100    512160
 Timer                                              Cum (sec)  Count  Avg (msec)
 page                                               424.547    1      424547.19
 destination import                                 421.709    100    4217.089
 field_collection_save                              418.984    100    4189.84
 saveIDMapping                                      0.948      100    9.484
 mapRowBySource                                     0.716      2204   0.325
 MigrateFieldsEntityHandler->prepare                0.27       100    2.704
 lookupDestinationID                                0.1        200    0.5
 MigrateDestinationEntity->prepareFields            0.061      100    0.613
 MigrateFieldsEntityHandler->complete               0.043      100    0.428
 MigrateDestinationEntity->completeFields           0.038      100    0.375
 MigrateValueFieldHandler->prepare                  0.008      200    0.042
 MigrateSourceSQL performRewind                     0.007      1      7.2
 MigrateSourceSQL execute                           0.007      1      7.11
 MigratePathEntityHandler->prepare                  0.006      100    0.059
 MigrateTaxonomyTermReferenceFieldHandler->prepare  0.004      100    0.044
 MigrateSourceSQL getNextRow                        0.004      100    0.041
 VildmedmadIngredientMigration prepareRow           0.003      100    0.035

```

I don't know what 'page' timer is but `field_collection_save` timer looks very suspicious.

**\[edit\]**

Similar issues happens when I do rollback. Same insane queries inserting lots of rows into `field_data_field_level_2` table for each removed filed collection. Here's weird thing though: I would expect that the rollback is slow at the beginning and speeds up when there is less rows to work with. But no! It started very fast and slowed down over time.

# Answer
> 0 votes
For those facing similar problem: the issue was caused by one node that had 3000+ `level 2` field collections. This was caused by a malformed source data. After fixing this, the largest `level 2` field collection set was roughly 50 entities and that worked fine. No slowdowns.

The problem with 3000+ field collections working slow was caused by `entity_save` that each time sent that humongous query to the database. It basically meant that each newly added field collection resulted in a query that contained all of the field collections for that particular entity.

This is insane, but that's how it works inside `entity_save`. The only workaround for that seems to be manually creating those entities or maybe even writing custom entity controller. Fortunately I didn't have to do that - fixing source data relationships solved the problem.

---
Tags: 7, entities, migrations
---


# Question
Title: Rankings and Dates in Views (data architecture)
I'm working on building a small name ranking database, but I'm having some issues coming up with how to architect the data. Here's the scenario:

You have a list of 100 names with rankings by year.

```
|  Name  | 2012 rank | 2011 rank | 2010 rank
--------------------------------------------
|  Carl  |    1      |     4     |    15
| Frank  |   40      |    18     |    34
|  Lou   |    8      |     6     |     4

```

et cetera and so forth. If each name was a node, how would that content type be set up so you can filter rankings by year?

Would you have a new field for each year that has the ranking in it? ie: Field name: 2012 Rank, value: 8.

Just curious how someone might approach this.

# Answer
I could propose using Entity Reference or Field Collection for the second item (Rank).

So, Rank should have 2 different fields eg an integer field (Ranking) and a taxonomy term reference (Year).

These modules will allow you for better data manipulation, Views integration, sorting etc.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: Send data with post to other drupal page not working
I'm trying to send data from a html form to another drupal page.

**The Form (in JavaScript):**

```
var data = { // JS Object with data to send
            priceUnit: '131.97',
            priceTotal: '131.97',
            priceCount: '1',
            articleNumber: 'XYZ'
        };
        // Form creation
        var form = document.createElement("form");
        form.style.display = 'none';
        // link to drupal site
        form.action = "../configurator/process_order";
        form.method = "post";
        form.target = "_blank";

        // Create form Content from JS Object data
        for (var key in data)
        {
            var input = document.createElement("input");
            input.name = key;
            input.value = data[key];
            form.appendChild(input);
        }
        document.body.appendChild(form);
        form.submit();

```

**On the other page, I am trying to access php `$_POST` but there is no output:**

```
<div>
     <?php
         echo $_POST['priceUnit'];
     ?>
</div>

```

**But, if I add `var_dump($_POST);` in my module: configurator.module:**

```
function configurator_process_order()
{
    var_dump($_POST);

    $modulePath = drupal_get_path('module', 'configurator');

    $content = file_get_contents($modulePath . "/Trader/PHPWebPages/processOrder.php");
    return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}

```

**I get the following output:**

```
array (size=4)
  'priceUnit' => string '131.97' (length=6)
  'priceTotal' => string '131.97' (length=6)
  'priceCount' => string '1' (length=1)
  'articleNumber' => string 'XYZ' (length=3)

```

So the form has submitted it's data but I cannot access it on my drupal page.
**What am I doing wrong?**

# Answer
Your code:

```
<div>
     <?php
         echo $_POST['priceUnit'];
     ?>
</div>

```

is probably in one of the tpl.php files. They are cached. You are not passing any data from any module to your template file, so Drupal cannot know it is not supposed to be cached. That's all.

Access post data in your module file, and pass it to your template properly, the "Drupal way" you can see in Examples, and you'll be good.

Also, I strongly suggest to remember that **POST data is user-agent provided and you should never trust it**. Especially not for things like price! There is a Drupal Form API to automate tests, but what you really should pass around is item's ID, and it's price should always come from your database, not from your user.

**Price supplied by client is a recipe for a legal disaster.**
> 0 votes

---
Tags: forms, 6
---


title: Modify field in node drupal 7

text:
# Question
Title: Modify field in node drupal 7
I have field "myfield" in a node. The field is created in the content, not by hook. I want to change the value of that field. I do not want to display the value from database, but my value let's say random number. I tried to do this with hook\_node\_view and with hook\_entity\_view but I cannot change it on the display. Here is my code:

```
function mymodule_node_view($node, $view_mode) {
  if ($node->type == 'my_node_type') {
    if ($node->nid == 46) {
      $node->myfield['und'][0]['value'] = 55;
//or I tried with $node->content and no success
    }
  }
}

```

What am I missing? Can you help me, please! Thanks you in advance!

# Answer
> -1 votes
You can use this line instead:

```
$node->content['myfield'][0]['#markup'] = '55';

```

---
Tags: entities, nodes, hooks
---


title: Query taxonomy term for given product

text:
# Question
Title: Query taxonomy term for given product
I have a node template, rendering a product list based on a query :

```
$productsQuery = db_select('commerce_product', 'p');
$productsQuery->join('commerce_product_type', 't', 't.type = p.type');

$productsQuery->fields('p')
    ->fields('t')
    ->condition('p.status', 0, '>')
    ->orderBy('p.created', 'DESC')
;

$results = $productsQuery->execute()->fetchAll();

foreach ($results as $product) {
    $productNodeQuery = new EntityFieldQuery();
    $productNodeQuery->entityCondition('entity_type', 'node', '=')
        ->propertyCondition('type', $product->type)
        ->fieldCondition('field_product', 'product_id', $product->product_id, '=')
        ->range(0, 1);

    if ($node = $productNodeQuery->execute()) {
        $node = array_shift($node['node']);
        // Render the node
    }
}

```

It is working well, but I do not access to the different fields of the product-display node in EntityFieldQuery...

For instance, In my product-display, I have a required relation to a taxonomy term, that I would like to display for each product.

How to get this specific field ?

# Answer
> 3 votes
An `EntityFieldQuery` just returns IDs, you need to load the entities manually:

```
$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node'));
  foreach ($nodes as $node) {
    if ($items = field_get_items('node', $node, 'field_foo')) {
      // ...
    }
  }
}

```

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


title: HTML change in A drupal site

text:
# Question
Title: HTML change in A drupal site
it has been suggested to me to delete this code piece from my site's files:

```
<link rel="shortlink" href="http://www.panchers.co.il/node/1" />

```

The problem is I haven't found the file which stores it... my theme is Pixture-Reloaded. thanks for your help.

# Answer
The default shortlink for the page is added by `node_page_view()`, but if you have Metatag enabled, it will override the default behavior.

I usually tackle things like this in a `hook_html_head_alter()`, eg

```
function MYTHEME_html_head_alter(&$head_elements) {
  // get rid of shortlink from metatag module
  unset($head_elements['metatag_shortlink']);

  // find the default shortlink from core, and zap it
  foreach ($head_elements as $key => $elements) {
    if (strpos($key, 'drupal_add_html_head_link:shortlink') === 0) {
      unset($head_elements[$key]);
    }
  }
}

```

The tricky part is that the element name from core doesn't have a consistent name, so you need to loop through find the right one to remove. If that doesn't remove it, then you need to `dpm($head_elements)` and figure out the proper element to remove.
> 2 votes

---
Tags: theming
---


title: Mass node update

text:
# Question
Title: Mass node update
I have a site containing several thousand nodes. Each node is effectively a book, in that it has a title, various content fields and a unique identifier similar to an ISBN.

I need a way of importing some data into the site via a script, using the unique identifier as a check - i.e. where ISBN = "X", update field body with "Y".

Can I do this via SQL or is there a better way?

# Answer
> 0 votes
To update a node in code, I suggest to use the entity module, since it is really much easier to manipulate its entity wrapper than the default node / fields objects.

For an example of use :

```
$node_wrapper = entity_metadata_wrapper('node', $node);
$var = $node_wrapper->field_number->value() + 1;
$node_wrapper->field_number->set($var);
$node_wrapper->save();

```

You can wrap your whole import into a transaction, to avoid errors :

```
db_query("begin;");

...

//if error
db_query("rollback;");

...

// if everything is ok
db_query("commit;");

```

All you have to do now is retrieve your nodes and loop through it :

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node', '=') // select nodes
              ->propertyCondition('type', 'news', '=') // node type
              ->propertyCondition('status', '1') // published
              ->fieldCondition('field_yourfield', 'yourfield_value', 0, '>') // your field condition
              ->execute();

$nodes = node_load_multiple(array_keys($result['node']));

```

And now you have everything you need !

Edit : since you dont need to learn how to build a module just for a one-time script, you can create your own script ... but with the drupal API. You can do this with :

```
// Get the drupal path
$drupal_path = $_SERVER['DOCUMENT_ROOT'];

// Define a DRUPAL_ROOT contant with the drupal path
define('DRUPAL_ROOT', $drupal_path);

// load the bootstrap.inc file to access the drupal_bootsrap() function
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

// Start drupal
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// You now have access to the drupal API, so you can do :
// var_dump(node_load(1));

```

---
Tags: importing-exporting
---


title: RDFa output and Panels

text:
# Question
Title: RDFa output and Panels
I need to get RDFa working with Panels. As it currently stands, fields output with panels or panelizer will have their `property` fields set correctly. You can see an example of this at http://schema.org/Product when you look at the bottom and view RDFa output.

The part that isn't working is getting all of the properties to be wrapped by their proper type, in this case Drug. So at some point, all of the output fields need to be contained within a wrapper that has the attribute `typeof="Product"`.

Panels has no support for this, but you can see an example of what it would look like if you looked at some sample node output. The node container wrapper would look something like this.

```
<div id="node-121" class="node node--product node--full node--product--full clearfix" about="/products/sample-product" typeof="schema:Product sioc:Item foaf:Document" role="article" itemscope="" itemtype="http://schema.org/Product">

```

That's your typical RDFa output when rendering output with `node.tpl.php`. Panels doesn't use this though, so it never gets rendered.

I'm hoping someone out there has dealt with this situation. Structured data is pretty common to see these days, and so is the use of Drupal with Panels. Someone has to have tackled this problem before, and I'm just looking for the best solution possible at this time. Thanks.

**TL;DR:** What is the best way to get RDFa working with Panels? Specifically, getting the `typeof` property added to some wrapper element which contains all of the other properties.

# Answer
> 0 votes
This is a known issue, and something I'm hoping to tackle at some point in the next couple of months: https://drupal.org/node/1485074 (see in particular comments #5 and #8). Feel free to subscribe to that issue as well.

---
Tags: 7, panels, rdf
---


# Question
Title: How to remove duplicate terms in a vocabulary
I have a vocabulary with many terms that are duplicates. How can I remove those terms?

I have many duplicates; I need a way to delete them that is not deleting them one by one.

# Answer
> 2 votes
Run this code once in hook\_init or custom php block or using drush

```
<?php

$vid = 1; // Replace 1 by vocabulary id for which you want to remove duplicates.

$terms = taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE);

// Loop through all terms in vocabulary
foreach ($terms as $term) {
  // Get all matching terms by term name
  $matching_terms = taxonomy_get_term_by_name($term->name);
  foreach ($matching_terms as $matching_term) {
    /* Check matching term belongs to vocabulary we are searching and matching term should not be exact term that first found so that duplicate can be removed */
    if ($matching_term->vid == $vid && $matching_term->tid != $term->tid) {
      // Do Term Delete
      taxonomy_term_delete($matching_term->tid);
    }
  }
}

?>

```

**Important Note:** Take Database backup before running above code, so that you can restore if something goes wrong !

# Answer
> 3 votes
The Term Merge module could help you.

> When using taxonomy for free tagging purposes, it's easy to end up with several terms having the same meaning. This may be due to spelling errors, or different users simply making up synonymous terms as they go.
>
> You, as an administrator, may then want to correct such errors or unify synonymous terms, thereby pruning the taxonomy to a more manageable set. This module allows you to merge multiple terms into one, while updating all fields referring to those terms to refer to the replacement term instead.

# Answer
> 2 votes
You can do this using the Rules, To do this:

```
**Event**
After updating existing content

```

I chose after updating a content so you can chose all nodes and select update, which can be unpublish/publish - update url alias, any will work.

```
**Conditions**
Content is of type

```

and enter your content type

```
**Actions**
Add loop

```

Make sure the loop loops through your tags, my tags machine-name is "field-basic-tags" so you would chose something like "node:field-basic-tags" in the loop Data selector.

then you would add an action to that loop,

```
Add an item to a list

```

Chose "list-item:parent" from the data-selector

And check Enforce uniqueness box and maybe you can also add,

```
Show a message on the site

```

to make sure your code worked.

here is an export of the rule.

```
    { "rules_enforce_uniqness_tag" : {
    "LABEL" : "Enforce Uniqness Tag",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "page" : "page" } } } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-basic-tags" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "list_add" : {
                "list" : [ "list-item:parent" ],
                "item" : [ "list-item" ],
                "unique" : 1
              }
            }
          ]
        }
      },
      { "drupal_message" : { "message" : "Done" } }
    ]
  }
}

```

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


# Question
Title: Can you preprocess a specific region in template.php?
In your template.php file, I know you can use theme\_preprocess\_region and check what "region" you are in, and accomplish what I am attempting like that...but I was wondering if you can do something like theme\_preprocess\_region\_specific\_region to further break things up and not have a lengthy preprocess\_region function? I can't seem to find any documentation on that.

# Answer
> 2 votes
Well, you can define your own preprocess function if you want to, since you have all the elements for that. In the theme\_preprocess\_region function, you can simple do :

```
$function = 'yourtheme_preprocess_region_'.$variables['region'];
if (function_exists($function)) {
  $function($variables);
}

```

Then, you just have to define the a function for your region :

```
function yourtheme_preprocess_region_YOURREGION(&$variables) {

}

```

---
Tags: 7, theming
---


# Question
Title: Is there a way to re-categorize content in a list form?
There are hundreds of content pages on a site I work with. These are categorized with Taxonomy, which connects the pages to the menu system. There is a need to revise these connections. I would like to create a page (view) where these Taxonomy references couyld be updated? Is this possible?

# Answer
Assuming I read your question correctly, you could try the Edittable Views module. details from its project page:

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
>
> Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
> 0 votes

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


# Question
Title: List taxonomy terms in node where the vocabulary is referenced
I have a taxonomy vocabulary called "Type of appendix". When adding a new node to the page, users can choose a type of appendix. When showing the node, it should list the all appendixes in a table with the category in the first column, the name in the second column and a link to the item in the last column. As shown in the image below

At the moment, my page displays the following:

I want to replace `ICT manual` with the table in the example.

# Answer
> 0 votes
You should be able to accomplish that with the Views Module:

> You need Views if
>
> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.
>
> Views can do a lot more than that, but those are some of the obvious uses of Views.

Depending on your folder structure, you can use a contextual filter and can create a block, then limit which pages on which it is viewable.

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


title: Why isn't my custom region showing up?

text:
# Question
Title: Why isn't my custom region showing up?
I'm trying to create a new region called 'usermenu' for my theme in Zen. I've therefore added

```
region[usermenu] = User menu

```

to the `mytheme.info` file, added

```
<?php if ($logged_in): ?>
  <div id="usermenu">
    <div class="menu">
      <?php print render($page['usermenu']); ?>
    </div>
  </div>
<?php endif; ?>

```

to the `mytheme.tpl.php` file and added

```
#usermenu {
  background-color: #fff;
  height: 35px;
}

```

to one of my CSS files. After clearing caches multiple times, the new region is displayed correctly and I can detect it with Firebug, but it doesn't show up in the block section.

What's going wrong and how can I solve this?

# Answer
I found it! It was just a stupid typo in the `.info` file. I should have inserted `regions[usermenu] = User menu`...
> 0 votes

---
Tags: 7, theming
---


title: Drupal Lightbox 2 not displaying image

text:
# Question
Title: Drupal Lightbox 2 not displaying image
http://www.wmfs.net/blackcountrylevel3plan

I have the Isotope working with Lightbox2, however the Lightbox is just displaying a blank space and not the image.

I am trying different things to troubleshoot the problem, different configurations in Drupal, putting the JS in the header and footer, there are no significant JS errors in Web Inspector.

Any help is gratefully appreciated.

Ant

# Answer
as i see in the console, you are using jquery.min.js?v=1.9.1

and lightbox.js is giving this error:

> TypeError: $.browser is undefined

because this function has been remove since 1.9

I'll suggest you to use default jquery version 1.4.2 where $.browser is deperecated but should work or use another ligtbox module like colorbox
> 2 votes

---
Tags: javascript
---


# Question
Title: How to install Drupal without interaction via web UI?
Is it possible to confgirue installation profile so it can be installed via web UI as usual but without any interaction, just the progress bar?

# Answer
> 5 votes
You can Install Drupal using Drush without interacting WEB UI. You have to use following command

```
drush dl drupal-7.x --drupal-project-rename=D7
cd D7
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://YourMySQLUser:YourMySQLPassword@localhost/YourMySQLDatabase

```

Ofcourse You have to install Drush if not already installed and change Mysql Database details in command as per details.

Choose installation profile that you want to install

**site-install standard** OR **site-install minimal**

# Answer
> 1 votes
Yes, definitely.

You'd end up coding an **install profile** (PHP) that directly answers all config questions (site name, db name, db user, db password, and so on). It's not hard, but there's already **Drush** that does this very well so you could consider triggering Drush in the background (using it's "site-install" command), then there'd be no progress bar from Drupal (but instead your own custom form/page with a progress indicator until the server \[Drush\] finishes preparing the new site/domain/folder.

Personally, I'd use Drush and hide it behind an authenticated form. But, if you can't use Drush for this, then look into generating your own settings.php file (with **$config** variables for everything needed - site name, URL, db name/user/pass, etc.)

# Answer
> 0 votes
Well, simplytest.me does something like that, but it also involves shell scripts and so on (you need to select a contrib module to skip the installer). simplytest.me is open source, so you can look at what it does.

It's not possible to do it without changing the installer I believe, although in Drupal 7, it used to be possible to pass the language and profile to it through the URL and if you had the database settings already in settings.php, it started the batch immediately, that no longer works in D8 but could possibly be restored.

---
Tags: installation, 8, distributions, installation-profiles
---


# Question
Title: Where do I find extensive taxonomy repositories?
Where might one find an extensive repository of taxonomy terms divided into different vocabularies?

Cheers,

# Answer
Take a look at Open Calais (http://www.opencalais.com/) They have an extensive tagging system that is free to use. They even have a Drupal module you can use: OpenCalais. Details from its project page:

> The Calais Collection is an integration of the Thomson Reuters' Calais web service into the Drupal platform. The Calais Web Service automatically creates rich semantic metadata for the content you submit – in well under a second. Using natural language processing, machine learning and other methods, Calais analyzes your document and finds the entities within it. But, Calais goes well beyond classic entity identification and returns the facts and events hidden within your text as well. The web service is free for commercial and non-commercial use. It requires registration to obtain an API Key.

You can use such a service to find/suggest tags for your corpus of content.
> 1 votes

# Answer
The Autotag module - as the name suggests - automatically tag blog posts etc. for you. You can choose what content should be autotagged. It relies on a third party service to tag content.

Opencalais provides a free service with up to a large number of transactions per day (50.000 immediately, can be extended). There are also other options but this seems to be the one that will work best in my case (multi-user blogs in a closed community).

I have found a module to import .CSV files: https://drupal.org/project/taxonomy\_csv However I have not found any repositories except for a list of public services where the tags themselves were numbers only the description showed what it meant.

So currently it seems the only two options are 1. creating vocabularies yourself or 2. rely on a third party service to do the work for you.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Change module settings stored in an array with drush
I would like to configure a module (addtoany) settings with drush. This is the variable:

```
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => page
    [legal] => 0
    [webform] => 0
)

```

So that, for instance:

```
[page] => page
[legal] => 0

```

becomes

```
[page] => 0
[legal] => legal

```

But I am rather new at drush and I am at a complete loss. Thanks for your time.

# Answer
> 8 votes
Drush does not have any mechanism to convert commandline arguments into php arrays for the variable-set command; however, it is easy to write short php snippets using the php-eval command ('ev' for short).

For example, if you have set up a site alias for your site called "@site":

```
$ drush @site ev 'variable_set("addtoany_nodetypes", array("about_us" => "about_us", "contact" => "contact", "page" => "page", "legal" => 0, "webform" => 0));'
$ drush @site vget addtoany_nodetypes
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => page
    [legal] => 0
    [webform] => 0
)
$ drush @site ev '$v = variable_get("addtoany_nodetypes", array()); $v["page"] = 0; $v["legal"] = "legal"; variable_set("addtoany_nodetypes", $v);'
$ drush @site vget addtoany_nodetypes
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => 0
    [legal] => legal
    [webform] => 0
)

```

If you are not using a site alias, then cd to the Drupal root of your site (or cd to the sites folder that contains settings.php if using a multisite) and remove the "@site" from the examples above.

# Answer
> 6 votes
As stated in the drush help documentation `drush help variable-set` the recommended way to set an array variable is using format=json:

```
php -r "print json_encode(array('drupal', 'simpletest', 'leftandright', 'category'));"  | drush vset --format=json project_dependency_excluded_dependencies -

```

*Don't forget the "**-**" at the end.*

---
Tags: drush
---