# Question
Title: AJAX: Form API Dependent Drop Down with more options
Started with the example here: https://api.drupal.org/api/examples/ajax\_example!ajax\_example.module/function/ajax\_example\_dependent\_dropdown/7

However, I then wanted to add a third option that was depended on the first two (which is not in the example given)

The problem I first ran into was that when I updated the first dropdown it would update the second, but not the third.

So I changed the callbacks from

```
function ajax_example_dependent_dropdown_callback1($form, $form_state) {
  return $form['dropdown_second'];
}

```

and

```
function ajax_example_dependent_dropdown_callback2($form, $form_state) {
  return $form['dropdown_third'];
}

```

to

```
function _ajax_example_dependent_dropdown_callback1($form, $form_state) {
  $commands[] = ajax_command_insert('#dropdown-second-replace', drupal_render($form['dropdown_second']));
  $commands[] = ajax_command_insert('#dropdown-third-replace', drupal_render($form['dropdown_third']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

function ajax_example_dependent_dropdown_callback2($form, $form_state) {
  $commands[] = ajax_command_insert('#dropdown-second-replace', drupal_render($form['dropdown_second']));
  $commands[] = ajax_command_insert('#dropdown-third-replace', drupal_render($form['dropdown_third']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

Which got me most of the way, but I still have one problem left. It seems that when I update the first dropdown, it updates the options in the second box but doesn't send the updated value into my options function to get the new options for the third box.

Here is my code:

```
function cquiz_create_exam($form, &$form_state) {
  $subjects = _cquiz_get_subjects();
  $selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : $subjects[key($subjects)];

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'Select Subject',
    '#options' => array_unique($subjects),
    '#default_value' => $selected,
    '#ajax' => array(
      'callback' => '_cquiz_create_exam_callback_first',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

  $type = _cquiz_get_type($selected);
  $selected2 = isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : $type[key($type)];

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => t('Exam Type'),
    '#prefix' => '<div id="dropdown-second-replace">',
    '#suffix' => '</div>',
    '#options' => _cquiz_get_type($selected),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    '#ajax' => array(
      'callback' => '_cquiz_create_exam_callback_second',
      'wrapper' => 'dropdown-third-replace',
    ),
  );

  $form['dropdown_third'] = array(
    '#type' => 'select',
    '#title' => t('Number of Questions'),
    '#prefix' => '<div id="dropdown-third-replace">',
    '#suffix' => '</div>',
    '#options' => _cquiz_get_number($selected, $selected2),
    '#default_value' => isset($form_state['values']['dropdown_third']) ? $form_state['values']['dropdown_third'] : '',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

```

In the $form\['dropdown\_third'\] section you can see that the options are defined by another function. That function doesn't get redone after changing the first drop down box. How do I get it to reload those options using the new select values?

# Answer
Not totally sure, but setting $form\_state\['rebuild'\] = TRUE in your submit or validation handler may help here.

> This is the key function for making multi-step forms advance from step to step. It is called by drupal\_process\_form() when all user input processing, including calling validation and submission handlers, for the request is finished. If a validate or submit handler set $form\_state\['rebuild'\] to TRUE, and if other conditions don't preempt a rebuild from happening, then this function is called to generate a new $form, the next step in the form workflow, to be returned for rendering.

https://api.drupal.org/api/drupal/includes!form.inc/function/drupal\_rebuild\_form/7

Another option would be to replace the entire form on in your AJAX callback. So essentially you'll specify a #prefix and #suffix for the entire form and then use that prefix element id in your $form\['dropdown\_first/second'\]\['#ajax'\]\['wrapper'\]. Your callback will look something like this:

```
function ajax_example_dependent_dropdown_callback($form, $form_state) {
  ...
  return $form;
}

```
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Override node template depending on menu settings
How do I override the template of a node based on where it is in the menu?

For example, I create a node, and within the "Menu settings" I put it under some "parent item". I wish to use a specific template for nodes of a particular content type that fall under a particular parent item.

# Answer
I figured it out by doing something like this in `theme_preprocess_page`

```
$link_path = "node/$node->nid";
$result = db_query('SELECT m.plid from {menu_links} m where m.link_path = :lpath', array(':lpath' => $link_path));

```

where plid, the parent menu id, is what I needed.
> 0 votes

# Answer
I believe it is possible to achieve this in `hook_preprocess_node` by calling `menu_get_item`, checking whether it is the item you are looking for (checking the parent etc.) and then assigning the appropriate template like this: `$vars['template_file'] = 'your_template_file';`
> 0 votes

---
Tags: 7, routes
---


# Question
Title: A views page as “Output this field as a link” in a block (Drupal)
Hello I´m trying to get a link from my thumbnails gallery http://www.nellens.com/home/photos to the full size gallery http://www.nellens.com/home/photos-full for each "Photo" content type that I have, but when I put the node (I tried with 2 methods, first creating a text field where I put the URL and another following this tutorial drupal.org/node/1215544, so I put in this case \[counter\]), but nothing overwrites my output link, it always lands to /content, showing all the fields of my content type, and I just want to show my full size pics fields only, not all the fields. My content type is made by a thumbnail image, the full size images that have relation between them and a tag field. So I did create all as in the FAQ tutorial but when I try to overwrite the thumbnail in the block to show the relative images and to land to the page /photos-full, it just does not work, it always lands me to /content.

Thanks in advance.

# Answer
Images can automatically be made to link to either their node or directly to the image itself using the 'manage display' tab on the content type: `admin/structure/types/manage/content_type/display`

I would simply make your view an unordered list of teasers and link each image to the file itself if you only want to display the image, or if you would like to have other fields such as a description you could select content and link it out to the node. I am not sure how you have your content type setup but best practice would be to have the fields setup similar to the screenshot below. You would have one image field per photograph and simply use the teaser display mode and image styles to display thumbnails in a listing.
> 0 votes

---
Tags: views, blocks, navigation
---


# Question
Title: Drupal 6 term based view not translating vocabulary terms
I have a dilly of a pickle here. Please do help if you can.

I have a site that uses internationalization translation to translate content. Some of the content is not translating. Specifically a "view" that is of type "term". All my other views are translating correctly.

Here is the configuration page of my vocabulary

Here is an example of the term translations.

Here is the view for the taxonomy term countries. The view here seems to not have the correct filters available. For node based views, you can add a filter called "node translation-language" and set it to filter on the current language. But with views based on taxonomies there is no equivalent "term translation-language". How are we supposed to filter out the extra taxonomy terms from the view.

This is an example of a view based on nodes that has the filter "term translation-language" My term based view is missing this filter

Here is the Countries view in action...notice that Haiti shows up for every language in it's non translated form (note that those are 3 different Haiti's)

Can someone please explain what I need to do to get a term based view translating and not showing extra terms?

Thanks,

David

# Answer
I *think* what you are trying to do is something along these lines:

Which here gives me:

And when I change the language, eg:

it then gives me:

I've set my vocabulary here up like so:

with translations (quickly done just for this so pardon the potential sloppiness)

and nodes translated like this (pardon the silly titles):

so if you are getting different results, check to make sure all of the various places you can set a language are similar.
> 1 votes

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


# Question
Title: Performance of site when loading 3000+ variables
I test all modules (custom + contrib) in one drupal base itself which has resulted in lot of variables. I was just curious what happens if live site had 3k variables ? Since all variables will be eventually global variables will it not require huge amount of PHP memory ? or is it not limited at all ? What is the alternate here ? `cache_get` with new cache table instead of variable\_get every where

# Answer
Yes, large variable tables are a problem.

Variables should only be used for small configuration flags and settings and not to store large structures for example.

But given a large amount of modules, dynamic variables like per-content type things you will sooner or later get into trouble.

No, there is no solution to this problem. The variables system will be replaced with the new configuration system from the CMI initiative for Drupal 8 which will hopefully be better at dealing with this.
> 1 votes

# Answer
My suggestion is,

We should not use cache\_get or cache\_set.Because this will reduce the php memory, but highly increase the slow down the site by querying the DB.

Your mentioned case is very rare.so use variable\_get.
> 0 votes

# Answer
The solution is to use something other than your DB to hand off info like this to your application. If you're on a shared or VPS host this will likely be memcached if you have the option I recommend using Redis.

Your cache, cache\_bootstrap, and as of about D.22 your field info will be served from in-memory caching nicely.
> 0 votes

---
Tags: performance
---


# Question
Title: How do I add the page number to the page title on drupal default paginated pages?
It has been recommended by an SEO consultant that for paginated pages the page number is included in the page title to avoid duplicated content. How do I achieve this?

I did this:

```
    function hook_pager_link($variables){
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574

  //put the pagination page number into the title tag
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  //add page
  $page = t('page');
  $pattern = '/' . $page . ' \d/';
  $title = drupal_get_title();
  preg_match($pattern, $title, $matches);
  if(!$matches){
    $new_title = $title . ' - ' .  t('page') . ' ' . ($page + 1);
    drupal_set_title($new_title);
    }
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

```

# Answer
Have you investigated the Page Title module? It, among other things, features

> **Pagination Suffix**: One of the things you may noticed about Drupal in terms of SEO is that whenever you go through a paged list of content, the page title never changes. Google Webmaster Tools will flag this up as a problem as you essentially have several different pages all being identified with the same page title. A new feature, introduced in Page Title 2.1, is the ability to append the page number as a suffix pattern. This means any URL which contains something like page=2 in the query string will also have an optional token pattern suffixed onto the end of it. Important: for this feature to work properly, you need to be running Token 1.12 or later.
> 4 votes

# Answer
If you have to set other tags or configration related to SEO I suggest you Metatag module, that helps also with page title.
> 1 votes

---
Tags: paging
---


# Question
Title: How is $search_results in search-results.tpl.php generated
Where is $search\_results generated?

I've got an Apache Solr search, and I want to reorganize the content in a certain way, and modifying the theming as well based on certain conditions, but all I have with $search\_results is a string with a list.

What I want is to segregate search results based on a value in the object that Apache Solr creates.

# Answer
> 2 votes
About theming results, you should have 2 templates: `search-results.tpl.php` and `search-result.tpl.php` (without s).

The first one allows you to theme the list, the second one (without the s) allows you to theme the results individually.

So I would advise you to use a hook to sort/filter the results the way you want (see answers from Clive and arrubiu), but use the templates to define the design you want.

# Answer
> 1 votes
It's generated in `template_preprocess_search_results()`:

```
foreach ($variables['results'] as $result) {
  $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
}

```

# Answer
> 0 votes
You could, in custom module, use hook\_apachesolr\_process\_results to manage results after they are returned from Solr.

But I don't know if this hook gives you what you need. Try it :)

---
Tags: theming, search
---


# Question
Title: Node empty fields behave badly when created with Entity Metadata Wrapper
**Problem**

Creating a node with the Entity Metadata Wrapper causes two frustrating results if select fields are left blank. (using `#empty_option` from the FAPI) .

(My form to create a node is pretty much just a more complicated version of the \[create a node in code\]\[1\] example).

**Display Problem**

Typically when a node is created and a select field isn't filled in, the field will not display at all.

However when using the Entity Metadata Wrapper to create a node, if you then view the node the empty field titles still appear.

**Indexing Problem**

More frustratingly, if the node is indexed in this state it appears to store a blank string, which will appear as a blank option in a facet and throw the following error on ticking the blank facet.

```
Notice: Uninitialized string offset: 0 in SearchApiFacetapiTerm->addFacetFilter() (line 86 of
/srv/www/mysite/public/sites/all/modules/search_api/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc).

```

**The Question**

Both of these problems, disappear if I edit the node and save it. So something is being called in this process, or creating a node normally that isn't called with the Entity Metadata Wrapper.

Has anyone seen this before? What could be being called in a normal node creation that's not being run with the entity metadata wrapper?

**Sample Code**

This is an extra code for a node with the select field `field_area`.

```
function createanode_form, &$form_state){

   $area_field = field_info_field('field_area');
   $area_values = list_allowed_values($area_field);

   $form['field_area'] = array(
     '#type' => 'select',
     '#title' => t('Area'),
     '#options' => $area_values,
     '#empty_option' => t("-None-"),
   );

   .....

  $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Submit'),
     '#weight' => 70,
  );

}

function createanode_form_submit($form, &$form_state) {

    $values = array(
      'type' => 'job_advert',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 1,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    $ewrapper->title->set('Test title');
    $ewrapper->body->set('A bunch of text about things that interest me');
    $ewrapper->field_area->set($form_state['values']['field_area']);

    $ewrapper->save(true);
    entity_save('node', $entity);
}

```

# Answer
> 1 votes
When an `#empty_option` is defined, it will be added as a label for the empty option in a select list. The value can be defined as well, it is keyed as `#empty_value`. See the documentation for form\_process\_select for more details. You will see that for required fields, the default `#empty_value` is an empty string.

That value is filtered out in \_form\_validate. I think it is being unset, and then when you call `$ewrapper->field_area->set()` you are actually passing `FALSE`, `NULL` or something else that PHP lovingly converts to an empty string.

I think you could solve it like this:

```
if (!empty($form_state['values']['field_area'])) {
  $ewrapper->field_area->set($form_state['values']['field_area']);
}

```

Or if you manually set the `#empty_value` to `'_EMPTY'`:

```
if ($form_state['values']['field_area'] !== '_EMPTY') {
  $ewrapper->field_area->set($form_state['values']['field_area']);
}

```

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


# Question
Title: Hot to pass an argument to #ajax['path']
I have a form with a radio buttons (inside div#edit-field-nomination-und). I need to call a following AJAX callback:

```
function _onfit_ajax_get_term_description_callback($term) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_html('#nomination-desc', $term->description)));
}

function onfit_menu() {
  // ...
  $items['ajax/onfit/taxonomy/term/%taxonomy_term/description'] = array(
    'title' => 'Get taxonomy term description by AJAX',
    'page callback' => '_onfit_ajax_get_term_description_callback',
    'page arguments' => array(4),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'delivery callback' => 'ajax_deliver',
  );
  return $items;
}

```

Here is an attachment code (I dislike it and I want to use #ajax\['path'\]):

```
Drupal.behaviors.onfitExampleBehavior = {
  attach : function(context, settings) {
    $('#edit-field-nomination-und input', context)
        .once('edit-field-nomination-und', function() {
          var url = '/ajax/onfit/taxonomy/term/' + $(this).val() + '/description'
          new Drupal.ajax('nomination-desc-wrapper', $(this), { url: url, event: 'change' });
        });
  }
};

```

Is it possible to attach AJAX callback to a radio buttons by the means of hook\_form\_alter? I don't want to use #ajax\['callback'\], because the entire form will be send during each AJAX call. I think #ajax\['path'\] must be a more lightweighted. But the problem is that I don't understand how to pass a selected radio item id to a #ajax\['path'\].

# Answer
> 1 votes
From the docs:

> It is possible to replace ajax\_form\_callback() with your own functions. If you do so, `ajax_form_callback()` would be the model for the replacement. In that case, you would change `#ajax['path']` from the default 'system/ajax' and set up a menu entry in hook\_menu() to point to your replacement path.

So you need to

1. Set up a menu callback (looks like you've already done that)
2. Copy `ajax_form_callback()` to that path's page callback function
3. Make the changes you need to. The function is very short so it should be obvious which bits you need.
4. In your form elements use this:

```
$form['foo'] = array(
  ...
  '#ajax' => array(
    ...
    'path' => 'path/to/new/callback',
  ),
);

```

You shouldn't write any JS code to invoke this manually, Drupal takes care of that for you.

Note that this method does load the full form; that's unavoidable using Drupal's built-in AJAX functionality.

---
Tags: ajax, forms
---


title: Fixing Overridden state for features

text:
# Question
Title: Fixing Overridden state for features
The feature are coming into override state always. After running 'revert', it goes into default state and everything is fine,however. My client are unable to do the revert every single time its being enabled. Why is it coming into override state always? There are no changes made... fresh install, enabled and it is in override state. Running diff shows:

```
Component type: fe_block_settings
        ),
        'cascade' => array(
<         'region' => 'page_header',
---
>         'region' => 'sidebar_first',
          'status' => 1,
          'theme' => 'cascade',
<         'weight' => -10,
---
>         'weight' => -1,
        ),
        'seven' => array(
        ),
        'cascade' => array(
>         'region' => 'help',
>         'status' => 1,
          'theme' => 'cascade',
        ),
        ),
        'cascade' => array(
<         'region' => 'sidebar_first',
<         'status' => 1,
          'theme' => 'cascade',
<         'weight' => -11,
        ),
        'seven' => array(
        ),
        'cascade' => array(
>         'region' => 'sidebar_first',
>         'status' => 1,
          'theme' => 'cascade',
<         'weight' => -9,
        ),
        'seven' => array(
        ),
        'cascade' => array(
<         'region' => 'navigation',
---
>         'region' => 'footer',
          'status' => 1,
          'theme' => 'cascade',
<         'weight' => -9,
---
>         'weight' => 10,
        ),
        'seven' => array(
        ),
        'cascade' => array(
<         'region' => 'user_popover',
<         'status' => 1,
          'theme' => 'cascade',
        ),
          'status' => 1,
          'theme' => 'cascade',
<         'weight' => -8,
        ),
        'seven' => array(

Component type: variable
      'api_version' => 1,
      'name' => 'site_name',
<     'value' => 'Cas<strong>ca</strong>de <i class="fa fa-bookmark"></i>',
---
>     'value' => 'Cascade Site',

```

As you see one is variable 'site\_name'. This variable is not changed, so i am coming to conclusion that when enabling the feature it is not setting the variable 'site\_name'. Can it be true? if so, why and how to fix? The same seems to be the case with fe\_block\_settings. I really would appreciate your help as this is becoming the case with many of my features. I would really like become good at troubleshooting and understanding features. Thank You a lot

# Answer
I think that if your feature set variables or configurations that are already stored on db, you have to revert it. instead this does not happen for "new" configurations.
> 1 votes

---
Tags: features
---


title: Change author field's empty behaviour

text:
# Question
Title: Change author field's empty behaviour
In the form to create a node, when the author field is not filled, the author is set to the anonymous user. I'd like to hide the author field when it is not empty.

Is there a Drupal workaround for that? I am really thinking into resolving this with JavaScript which I consider a desperate approach.

# Answer
If you are talking about this portion of the node's display:

```
<?php if ($display_submitted): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```

you could use `hook_preprocess_node()` to accomplish this in either your theme or a custom module, eg, something like this:

```
function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  if (!$variables['node']->uid && $variables['node']->type==CT_TYPE) { // eg uid is 0 (anonymous) and this is the type of node we are looking for
    $variables['display_submitted']=FALSE;
  }

  // any other preprocessing goes here

}

```

The only difference really is if it were in a custom module, then it would apply across all themes.
> 1 votes

# Answer
Unfortunately you've no way to find **everywhere** this info will appears, as it will depends of the modules/templates that you're using.

So you need to identify where it is displayed, and check if user id is equal to 0 ( 0 = Anonymous user).

You can do this in hook\_preprocess for example, or just add a condition in your template. Like for example the default node.tpl.php is like this:

```
<?php if ($display_submitted): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```

You could add this condition to hide the infos for anonymous user:

```
<?php if ($display_submitted && $uid != 0): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```
> 1 votes

# Answer
You could work on theme, and in THEME\_preprocess\_node "unset" author output if author is anonymous.
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Create backup of MySQL database alongside Features module
When collaborating with other developers, we are using Features module and push it to a repository, this way the files can be pulled to the developer's own development environment.

Our problem is the database. What we do is export a SQL dump, and send it. Then import the SQL dump.

Is there a better way on handling database backups? Since I believe that Features module can't export the database.

# Answer
It's hard to encapsulate *every* db configuration value into a Feature. And, Features was never designed to do that. A Feature was originally supposed to be a re-usable site component.

To capture more fully site configuration look at the Configuration module:

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.
>
> For the most part this module provides the same functionality as a subset of the features module. Features module is currently the go to tool for moving configuration from environment to environment and site to site, and it does a great job doing this, but "configuration management" was never really what features was intended to do. The goal of features module was to group configurations together to satisfy a certain use-case. Instead most people use features to export configuration to code to ease with deployment between environments. Many of us have experienced the shortcomings of using features module for configuration management and found where it doesn't quite work to easily manage configuration. A couple other modules have spawned off to help with some of these shortcomings: features override, features plumber, Features Tools.

Additionally since not everything can be captured in Features, look into building your site via a `Installation Profile` where you can codify new Users, Content Types and custom variables as well.

I am currently using Features + an Installation Profile to *build* a webapp that lets notified individuals via email submit a Drupal Webform via a secretly keyed url parameter. You can use features (to an extent) but you really have to use many small features to get the job done, and not all modules play well with Features (like exporting Webforms, which requires node\_export, uuid and THEN features) ...
> 0 votes

---
Tags: database, features, backups
---


# Question
Title: Disable a field for input, without deleting it (to not lose old data)
I have a field in my customer profile (shipping/billing, doesn't matter which). I don't need this field anymore on checkout, but I want to keep the data of older orders. (this can be extended to any entity type, it just happens that commerce customer profile is my use case)

Is it possible to somehow disable the field for input, but not really delete it?

Ideally with a UI solution. I already know hook\_form\_alter() would do the trick..

# Answer
> 2 votes
You can use the Field Permissions module to remove permissions for users to access the field.

---
Tags: entities
---


# Question
Title: Insert a Views Block into a node in Drupal 7
\[Drupal 7\]

I have a block I created in Views called "handy\_tips-block\_1".

Now I want to insert it into the body field of my node.

How do I do this?

I found a guide on here, which suggests to use the following code:

```
<?php
print $block = module_invoke('views', 'block_view', 'handy_tips-block_1');
print render($block['content']['#content']);
?>

```

However, all what is printed out are the words "Array". (I have enabled the PHP input filter for the body field).

Note: in the posted code, I have also tried substituting 'views' with various items such as "block". I have used 'handy\_tips-block\_1' as the ID, because that is what is displayed on the configuration link of the block administration page.

# Answer
> 15 votes
Output is "array" because indeed is an array, then I guess that you want to print your array to see what fields you can use:

```
print_r($block);
print_r($block['content']['#content']);
print_r(render($block['content']['#content']);

```

About display a View, you can use this line of code inside your template, to call a view:

```
echo views_embed_view('view-name', $display_id = 'display-name');

```

for example, inside my node.tl.php I want to insert a view called `test view` and I want to use his Block display with machine name `block_test`, then I can use:

```
echo views_embed_view('test_view', $display_id = 'block_test');

```

(Remember to use the **machine name** of your view and **machine name** of your display).

I hope this information will be useful.

# Answer
> 8 votes
My favorite way to embed views in template files is with the views\_embed\_view() function.

It's really easy to use:

```
<?php print views_embed_view('view-name', 'display-name','arguments'); ?>

```
* The 'display-name' argument corresponds to the type of display in your view, and the number of those types of there are multiple. So if in your view you created two blocks, you could call one or the other by using 'block-1' or 'block-2' in the 'display-name' argument.
* The third argument, 'arguments', is optional, and can be used to pass any contextual filter arguments your view depends on.

# Answer
> 5 votes
I recommend using either the Entity Views Attachment module, which allows you to insert a view into your module as if it's a field, or the Display Suite module which allows you to customize your node lay-out and insert all kinds of blocks into it.

# Answer
> 1 votes
I realise this is an old thread now, but I was looking for this too and found the BlockReference module. It allows you to associate a block with a node as a field.

It works a treat!

---
Tags: 7, blocks
---


title: Mix Honeypot and Regcheck module?

text:
# Question
Title: Mix Honeypot and Regcheck module?
newbie question...

Hi,

Before "exploding" my site, I would like to know if I can mix :
\- https://drupal.org/project/honeypot
\- https://drupal.org/project/regcheck

I'm trying to stop the registration process before sending a request to the server (regcheck) and still have an efficient protection from spam (honeypot).

More generally, is mixing antibot modules a good idea?

Thanks.

# Answer
> 2 votes
While it probably will do no harm, there is not much point in using both.

**Regcheck** is a small and super simple module that will add an invible (to humans) checkbox on your registration form. Bots will check this, and when the bot submits the form, it can be rejected.

**Honeypot** is a larger and more complex beast that do several thing to block 'bots. One of these thing is to let you add an invisible (honeypot) field to *any* form - including the registration form. From the Honeypot docs:

> Honeypot form protection means that an invisible field is added to a form. If this invisible field is filled out (bots will usually put in a value), then the form will return an error. Normal users (read: human beings) won't ever see the field, so they won't fill it out.

If you install both, your registration form will have *two* invisble (to humans) fields. There is little harm in that (having both installed will consume slightly more resources), but not much benefit either .

So I suggest you install **Regcheck** if you want a simple solution with minimal configuration just to stop 'bots from registering, and **Honeypot** if you want a more comprehensive anti-spam solution.

However, if you're looking for a solution that stops bots *before* they hit the registration form submit button, neither **Regcheck** nor **Honeypot** will help. Both work by automatically dismissing registrations *after* they've been submitted.

If you want to block bots from *trying* to register, you can't do this by Drupal alone, but need to use webserver access rules.

There are projects, such as Project Honeypot (no relation to the **Honeypot** module) and Fail2ban that will do this for you.

To set up a Drupal site to use the Project Honeypot blacklist of IP-addresses, there is also a Drupal module, http:BL. AFAIK, there is no Drupal module for Fail2ban, but since it work directly with the the server, you don't need one.

# Answer
> 0 votes
You should be able to use both modules together though I think they overlap in their abilities. regcheck focuses only on the registration form and honeypot should be able to work on any form. So you should be able to get by without regcheck.

---
Tags: 7, advertising
---


# Question
Title: Why does my site fail after restoring the database?
I tried migrating my Drupal live site to localhost to test it there. I followed the instructions in Migrating a site.

* Cleared the cache
* Disabled clean URLs
* Enabled mod\_rewrite

Then I backuped my live site database. On my localhost, I created a database with the same name as my live site and ran a clean install of Drupal 7.25. Everything worked. I installed the *Backup and migrate* module, and tried to download the database; after submitting the form, the local site simply became blank and I could not access it.

I checked the local database and found that the backup database was properly copied into it. So, probably, the issue is not with the database access permissions on localhost.

I cannot figure out what causes the local site to fail.

What are the possible reasons for such a failure?

# Answer
> 0 votes
I found the reason of mistake. I accidentally put Entity module into the core and it generated WSOD when I tried to restore the database on my localhost. You should never put contributed modules into core modules folder.

---
Tags: 7, database, backups
---


# Question
Title: Database corruption after trying to reinstall Rules Module
I was getting a database error when trying to op the Rules UI so I tried to reinstall the module. I uninstalled the Rules Modules and Rules UI module then tried to install the Rules module and now every page of the sites gives this error:

```
Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sgda_arcade.rules_config' doesn't exist: SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 152 of /srv/arcade/sites/all/modules/custom/entity/includes/entity.controller.inc).

Additional

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sgda_arcade.rules_config' doesn't exist: SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 152 of /srv/arcade/sites/all/modules/custom/entity/includes/entity.controller.inc).

```

Is there anything I can do to fix this?

# Answer
> 0 votes
As it turns out the drive on which my database was installed had run out of disk space, so as JimaJamma suggested, the table could not be created by the rules module.

---
Tags: rules, database
---


# Question
Title: Behaviors/JQuery: What's the standard/convention in Drupal 7 for running Jquery code on event *OTHER* than DOM ready?
Searching online docs so far and I've found much about Drupal Behaviors running when the DOM is ready i.e. the `ready` JQuery function.

But what about for example if I want my JQuery code to run once all the images have loaded? Now, I *could* use the JQuery load function, but this is apparently not recommended to use such Jquery functions JQuery directly in Drupal but work within Behaviors instead - but these are no good to me if they only run on DOM ready event.

Thoughts?

# Answer
> 2 votes
Using `.load()` on element to attach event handler in your behaviors should not be a problem. Using it directly to `window` outside a behavior, for instance to wait for all images to be loaded, should be okay too.

As pointed by Clive in the comment, Drupal behaviors are to be used in replacement of `$.ready()`, not `$(window).load()`. However, if content (ie. new DOM elements) is added to the page after page load (AJAX calls, content generated from JavaScript, etc.), handlers for `$.ready()` will not be called and will not have a chance to process the added DOM elements. While the `attach()` method of all behaviors is also called when this happen. With a parent of the added DOM elements as `context`.

Behaviors can also have a `detach()` method which is called when DOM element are removed or before form serialization. This us, for instance, used to properly destroy WYSIWYG editors when their `textarea` are removed from the DOM and to prepare the POSTed data hen their form are submitted.

Off course, this rely on the JavaScript doing the addition/removal/serialization to properly call `Drupal.attachBehaviors()` and `Drupal.detachBehabiors()`. Something that is done by Drupal core (including form handling and the Drupal AJAX Framework) and properly written contrib modules.

I'm not familiar with the `load` event and its behavior with content added after the first time it is triggered. If it does not fire multiple times, re-registering the handler in a behavior `attach()` method may be required to ensure newly added image are also processed.

---
Tags: 7, media, javascript
---


# Question
Title: Form posting before ajax can update content
My form is submitting faster than ajax can update my textarea. How can I delay the form from submitting so the ajax can update my textarea?

```
$form['submit']['#ajax'] = array(
'callback' => 'getCampaignString',
'event' => 'submit',
'wrapper' => 'Comments_replace',
'method' => 'replace',
);
$form['submitted']['Comments']['#prefix'] = '<div id="Comments_replace">';
$form['submitted']['Comments']['#suffix'] = '</div>';

 function getCampaignString(&$form, &$form_state){
    $campaingString = $form_state['values']['submitted']['campaignstring'];
    $comments = $form_state['values']['submitted']['Comments'];
    $comments = $comments."[".$campaingString."]";
    $form['submitted']['Comments'] = $comments;

    $form['submitted']['Comments'] = array(
        '#type' => 'textarea',
        '#title' => t('New Comments'),
        '#name' => 'submitted[Comments]',
        '#value' => $form['submitted']['Comments'],
    );

    return $form['submitted']['Comments'];

}

```

So basically I have this webform for getting leads. There is a textarea for comments on the form. What I need to do is append a string to the end of the comments text on POST. For example: Say they made a comment like "I want more information" and when they hit submit. I need to add a string to the end of the comments so in the post it will look like this: I want more information - campaignName. The only way I have found to add my campaingname to the post of the comments is to replace the textarea with the new information in it but I cannot seem to replace it fast enought when submitted.

# Answer
> 0 votes
```
function THEME_form_alter(&$form, &$form_state, $form_id) {
    $form['#validate'][] = 'webform_validate';
}

function webform_validate($form, &$form_state) {
  //Appending comments field with campaignString
  $campaingString = $form_state['values']['submitted']['campaignstring'];
  $comments = $form_state['values']['submitted']['Comments'];
  $comments = "[".$campaingString."]  " . $comments;
  $form_state['values']['submitted']['Comments'] = $comments;
}

```

---
Tags: forms, ajax, webforms
---


# Question
Title: How to alter checkout panes based on order contents
I want to remove billing and payment for free orders. Currently, I have the code below.

Am I safe to user global $user in this case? Is there any better way to get the user account & order involved when this hook runs?

I ask because, after installing this hook, I've seen payment and billing panes hidden under admin/commerce/config/checkout, but I didn't hide them there. This seems to be intermittent.

```
function MODULE_commerce_checkout_pane_info_alter(&$checkout_pane) {

  global $user;
  $order = commerce_cart_order_load($user->uid);
  if (!empty($order)) {

    //get the order wrapper and order total
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_total = $order_wrapper->commerce_order_total->amount->value();

    // hide payment and billing info if the order total is <= 0
    if ((int) $order_total <= 0) {
      $checkout_pane['customer_profile_billing']['enabled'] = FALSE;
      $checkout_pane['commerce_payment']['enabled'] = FALSE;
    }
  }
}

```

# Answer
You're seeing them hidden on the admin page because you're making no differentiation here in your code that would restrict the checkout pane info altering to only occur on checkout pages for customers, not administrators.

I'm divided. I recently created a checkout experience with an optional checkout pane, and I ultimately decided to alter the form directly instead of altering the checkout pane info. Part of it was that desire to ensure I had an identical definition on the front end / back end for all customers, but I'm not sure it was strictly necessary.

If you do end up altering the form instead, you need to supply new custom validate / submit handlers for the conditional checkout panes that wrap their default handlers and only invoke them if the pane was actually presented on a checkout form.
> 2 votes

---
Tags: commerce
---


# Question
Title: Provide contents of file field at node URL
I'm trying to set up my Drupal website to host files (more specifically, PDFs) at clean URL's and have some download statistics about them. For example, I would like "test.pdf" to be available at "/publications/test.pdf". I read about all the file managers such as IMCE, but they do not seem to provide this feature. Therefore I'm now trying to set up a Publication content type with just a single field of type File, use the URL path settings to get the clean URL and use the Download Count module to provide me some download statistics. However, I cannot seem to have Drupal return the PDF in the file field when a user visits the URL of such a node. The closest I get is rendering a link to the file, using the display settings of the file field.

Is this the way to go for what I want to achieve? And if so, how can I provide the contents of a file field at the URL of the node containing that field?

Thanks in advance.

# Answer
Its not a good idea to provide contents of file field at node URL.

Instead use File Aliases module which will let you use node properties in the resulting file url.

> The File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., no more '/sites/default/files/').
> 2 votes

# Answer
The answer by Gokul N K is the way to go. However, some refinements to save those looking to use this module some time:

* The current version (7.x-1.0-beta1) has some bugs. These have been fixed by a great patch. To apply this patch though, you need version 7.x-1.x-dev dated 2011-Nov-15. This is not the development version with the same name, so fetch the version from november 2011 using the repository viewer.
* Then, to use the module: construct a content type, add a File field and look into the settings of that field. Took me forever to find out :)

Thanks!
> 0 votes

---
Tags: files
---


# Question
Title: Complex View Involving Separate Entities / Taxonomy Vocabulary / Content - Distinct
Given the following Content Type: **Smartphone**

**Taxonomy Vocabulary: OS:** Android / iOS / Windows / Blackberry

**Taxonomy Vocabulary: Color:** Red / Blue / White / Black / Yellow

OS and Color is a Taxonomy Vocabulary which is term referenced in the content type smartphone.

**Now the question is:**

How do you setup a view to display only the **COLORS** that are available for the Android OS? I do not care about what phone it is. Example of this contextual path would be: example.com/android-colors

That in effect would just give me a list of all available colors that androids are in. Since OS and color has no direct relation, you would have to create a view of smartphones then GROUP THEM BY color while the contextual filter grabs the %android% arguement via the path.

The problem with this is that there will be thousands of records since each result is unique since your querying the smartphone table. Distinct setting in the query dialog box does not apply since each result is technically not distinct.

# Answer
> 0 votes
You can cheat a little and use Views Limit Grouping to help do this.

I created a view of smart phones with the path being `smart-phones/%/colors`. The only argument I need is for the OS. Add a contextual filter for the mobile OS using "Content: Has taxonomy term ID", filter by the term name. Under your fields to be shown, just select the color.

Using the Group Field (with Limit) formatter, we'll group by the color and show 0 items. Now if there are smart phones that have a color selected, it should show up in this list. In my screenshot you can see that I am only showing Blue and Orange, but in my taxonomy I actually have Blue, Green, Orange, and Red available - but I have no phones that are Red or Green.

From here, all you need to do is rewrite the color url to go to whatever other view you would like, such as `smart-phones/%OS/%Color`

---
Tags: 7, views
---


title: Term parent in node.tpl.php

text:
# Question
Title: Term parent in node.tpl.php
I have an Entity taxonomy Reference field in my content type.

I need to print parent of the term linked to my node in node.tpl.php (link to that term). How can I do it?

Thanks for your help.

# Answer
Ok, I figured it out. This is my code:

```
<?php
    $term = field_get_items('node', $node, 'field_taxonomy_term');
    $parent = current(taxonomy_get_parents($field[0]['target_id']));
    print l($parent->name, 'taxonomy/term/'. $parent->tid);
?>

```
> 0 votes

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


# Question
Title: How do I remove webforms from content types?
Currently, our site is built so that anytime a specific type of new content is created, the page automatically includes a form required for the end user. Due to tracking issues we're having with other software, we would like to remove these automatic forms from this specific resource type so that the resource is no longer gated.

Can anyone explain how I can make this change to my current content type so that we're not forced to create a whole new content type and replacing things systematically?

# Answer
> 0 votes
If you use the webform module (I'm not 100% sure from your question), and you want to disable the webform functionality for the content type, then you can do this on the settings page of the content type (Admin \> Structure \> Content types). There should be a a fieldset or vertical tab called "Webform", and when you click on that there should be a checkbox that you can disable.

But be aware that this removes the form from all previously created nodes too, not only for the new ones.

If you're not using webform then please specify what modules do you use so that we can understand how this functionality is build into your site.

---
Tags: forms, nodes
---


# Question
Title: How to put a comma between city and state in addressfield display?
I'm using the addressfield module with Drupal 7.10. I want a comma after the city name when displaying the addressfield. Currently addresses display like:

```
123 Main St
SomeCity California 90100

```

I want it to display like:

```
123 Main St
SomeCity, California 90100

```

(Note the comma after "SomeCity")

How can I achieve this?

**UPDATE**

This whole formatting of addresses is still shrouded in mystery for me. I'm starting to think the way to control the formatting is to create a custom ctools plugin. I found this api documentation:

http://api.drupalhelp.net/api/addressfield/addressfield.module/group/addressfield\_format/7

I'm going to explore it.

# Answer
> 2 votes
This is actually pretty simple, once you know the hooks and have some example code. You're correct that you need to use the ctools plugin api. So in a custom module, add:

```
/**
 * Implements hook_ctools_plugin_directory().
 */
function mymodule_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/addressfield/' . $plugin;
  }
}

```

Then you drop plugin files in the directory you specified, within your custom module. In this case, plugins/addressfield. A file that will do what you're looking for would contain something like this:

```
<?php
/**
 * @file
 * city-comma.inc
 *
 * Adding comma after city.
 */

/**
 * Plugin definition for address field format.
 */
$plugin = array(
  'title' => t('Comma after city.'),
  'format callback' => 'mymodule_city_comma',
  'type' => 'address',
  'weight' => -80,
);

/**
 * Callback for plugin definition.
 */
function mymodule_city_comma(&$format, $address, $context = array()) {
  if (in_array($address['country'], array('US', 'CA'))) {
    if ($context['mode'] == 'render') {
      // Add comma after city.
      $format['locality_block']['locality']['#suffix'] = ',';
    }
  }
}

```

This file would actually go in a directory called 'formats' inside the directory defined in the hook. So: `mymodule/plugins/formats/city-comma.inc`.

# Answer
> 1 votes
Sure you can, but this needs some PHP skill.

Basically, you're going to override theme function responsble for rendering this field, which is `theme_addressfield_container()` in this case.

From function's declaration in theme\_addressfield\_container() you can see that all address attributes are being imploded. You can easily override this function to get the result that you want.

# Answer
> 1 votes
Open your theme folder, Put this code in template.php

```
<?php
// Putting comma between City and State of address field
function YOUR_THEME_NAME_addressfield_container(&$variables) {
  $element = $variables['element'];
  if($element['#title'] == 'City') {
    $element['#children'] = trim($element['#children']) . ',';
  }
  $element['#children'] = trim($element['#children']);
  if (strlen($element['#children']) > 0) {
    $output = '<' . $element['#tag'] . drupal_attributes($element['#attributes']) . '>';
    $output .= $element['#children'];
    $output .= '</' . $element['#tag'] . ">";
    return $output;
  }
  else {
    return '';
  }
}
?>

```

# Answer
> 0 votes
You're correct that Addressfield uses Ctools plugins.

I suggest you take a look What are Ctools plugin (content type, access, etc), and how does one create them? where I show how to create new plugins.

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


title: Change admin panel template

text:
# Question
Title: Change admin panel template
I created a custom template and by mistake i chose my template as a adminpanel template.

that got rid of the dashboard. how change the template to default template.

# Answer
Go to your-site/admin/appearance page, remove the styles (in Firefox is View/Page Style/No Style) and find the Administration theme form.

Select seven as administration theme and save configuration.
> 0 votes

---
Tags: theming, users, dashboard
---


# Question
Title: Drupal 7 - How to display the TID of a term reference field in a content type?
I have a content type called video and a term reference field called category. I want to be able to output the TID of the term reference field in my content display. Is there a way to do this to expose the TID of the term? I'm able to generate a link from the term in the manage displayed settings, but it has an alias to it so it won't show the tid in the url.

# Answer
> 1 votes
The best way to do this is to make a new field formatter. You need to implement two hooks, `hook_field_formatter_info()` and `hook_field_formatter_view()`. The info hook tells Drupal about your formatter and the view does the heavy lifting. You can then use this on the **Manage Display** for the field in your content type.

The easiest way to do this is to clone them from taxnomy.module, and modify. Something like this would be a start

```
/**
 * Implements hook_field_formatter_info().
 */
function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_term_name_with_tid' => array(
      'label' => t('Term name + tid'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'MYMODULE_term_name_with_tid':
      foreach ($items as $delta => $item) {
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name  : $item['name']);
        $element[$delta] = array(
          '#markup' => check_plain($name) . '(' . $item['tid'] . ')',
        );
      }
      break;
  }

  return $element;
}

```

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


title: Alter webform select option values

text:
# Question
Title: Alter webform select option values
I'm using a custom module to change subject and recipient email. Actually my fields are a single text field for the subject, and a select field for recipients.

I would like to add a more options actually. My webform is on a public page opened to all. I add a new page with a link to the contact form and I want that link to provide some options.

So my link is like this: `/node/5?option=1`

This bring me to the aforementioned page and set the subject field according to my custom module like this:

```
function ca_formdispatch_form_alter(&$form, &$form_state, $form_id)
{
    $nid = arg(1);
    drupal_set_message(t(" webform_client_form: .", $form_id));

    //determination de l'ID du formulaire afin de l'alt�rer
    if ($form_id == 'webform_client_form_5' && $nid == 5)
    {
        $origine = $_GET['origine'];

        drupal_set_message(t("contenu d'origine : @origine.", array("@origine" => $origine)));

        //liste des email destintaire possible en fonction de l'origine du destinataire

        switch ($origine)
        {
            case '1':
                $email_dest='xxx@example.com';
                $sujet_mail="Message pour 1";
                break;
            case '2':
                $email_dest='xxx@example.com';
                $sujet_mail="Message pour 2";
                break;
        }

        //affectation de la valeur de $email_dest comme email destinataire du message,
        $form['submitted']['destinataire']['#default_value']=$email_dest;
        drupal_set_message(t("contenu de email : @email.", array("@email" => $email_dest)));

        //affectation de la valeur de $sujet_mail comme sujet du message
        $form['submitted']['sujet']['#default_value']=$sujet_mail;
        drupal_set_message(t("contenu de sujet mail : @sujet_mail.", array("@sujet_mail" => $sujet_mail)));
    }
}

```

It works for the subject field but not for the recipient field. My recipient select field can take 4 options. I can set the select on an existing key but not add a new key not provided by the select by default.

I would to lock the key set by the module or hide the select field to don't allow is change by the user that did click on the link before.Is it possible? I know I can use `hook_webform_select_options` or `hook_webform_select_options_alter` but I don't know how with to make this code ... if someone could help me.

EDIT: i test this to get the "key" and pass it to the webform field but i think it doesn't work.

```
switch ($origine) {
  case 'charge-relation-entreprise'://valeur de $origine
  $clef="Chargé des Relations Entreprises";
  $email='web@pro.com';
  break;....

$form['submitted']['choisissez_votre_destinataire']['#options'][$clef] = $clef;
$form['submitted']['choisissez_votre_destinataire']['#value']=$clef;
$form['submitted']['choisissez_votre_destinataire']['#key']=$clef;

```

but if this display the right text in the select,it doesn't send mail...

EDIT2 : i get the right key label displayed if i set a default value key in the webform select list setting like here https://computing.artsci.wustl.edu/help/drupal-webforms-advanced

But my select doesn't work anymore if i go to the webform page directly,whithout instructions in the url.Like with the edit1

# Answer
For select fields to accept a default value, this value must be part of the `#options` list.

So you have to add the option before you can set the default value (important is the array key):

```
$form['submitted']['destinataire']['#options'][$email_dest] = $email_dest;
$form['submitted']['destinataire']['#default_value'] = $email_dest;

```

Then to hide the form element you can do:

```
$form['submitted']['destinataire']['#access'] = FALSE;

```

Or to keep it visible but disabled:

```
$form['submitted']['destinataire']['#attributes']['disabled'] = 'disabled';

```

But in any case, the submitted value for select elements **must** be part of the options list, otherwise it won't be accepted as a valid submission value. This is one of the many ways that Drupal tries to prevent malicious form manipulation.

For the difference between `#value` and `#default_value`: if `#value` is set, then it doesn't matter if a user chooses a different value for the form element. The finally submitted value that arrives in the submit handler will be the value set with `#value`. It's hardwired so to speak. `#default_value` on the other hand is more like a suggestion, it is changeable by the user and whatever is chosen will also arrive at the submit handler.
> 3 votes

# Answer
To set a default value on a select list, you need to use “#value” and not “#default\_value”. So in your case it will be:

```
$form['submitted']['destinataire']['#value']=$email_dest;

```

Hope it works. Good luck!
> 0 votes

---
Tags: hooks, webforms, forms
---


# Question
Title: How do I show an image using a relative or external url?
Seems like a simple issue but can't find a simple solution.

Basically I have the feeds module populating a content type from another database which has relative URLS of images. ie. `/images/image1.jpg`

I'm storing this value in a text field type.

Is there a way to easily translate the output of this field into `<img src="$value">` ?

# Answer
Sure, assuming Drupal 7, you can create your own field formatter for this in a custom module:

```
/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {

  $info = array();

  $info['image_source_formatter'] = array(
    'label' => t('Image Source Formatter'),
    'description' => t('Display the image sourced in this field.'),
    'field types' => array('text'),
  );

  return $info;

}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'image_source_formatter':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'image',
          '#path' => $item['safe_value'], // you can also set '#height', '#width', '#alt', '#title' and '#attributes' here as well, see theme_image() for more details
        );
      }
      break;

  }

  return $element;

}

```

Clear your caches to be on the safe side, and then you can use this new field formatter for this field, eg, you can go to the Manage Display in your Content Type and select this:

for the plain text field and instead of outputting the text, it will theme the text as the path to an image.

In this field, you can have `sites/default/files/foo.jpg` if you want and it will source it locally, or you can have `http://www.example.com/foo/bar/baz.jpg` and that'll work as well, as this will call theme('image', $variables) with the path set to the value of this field.

ADDITION: The URL Formatter and Simple Field Formatter modules appear to do this for you if you don't want to create your own custom module.
> 1 votes

# Answer
The easiest way to do this would be overwritting the field template

field-name-\[field\_name\].tpl.php

You can then just simply add your markup

Example:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><img src="<?php print render($item); ?>" /></div>
    <?php endforeach; ?>
  </div>
</div>

```

The $items array provides an array of information for that item and uses render to render the output. See the field template in the drupal api for more information https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7

If you are using Display suite https://drupal.org/project/ds then you can create a custom field to output that value alongside the token module. See this blog post for more details on that: http://www.elevatedthird.com/blog/using-custom-fields-display-suite-drupal-7
> 0 votes

---
Tags: theming, entities, nodes, media, feeds
---


# Question
Title: One of my drop down menus, the "Create Content" option under the parent "Content" tab has dissapeared. How can I recover it? (I'm using Drupal 7)
One of my drop down menus, the "Create Content" option under the parent "Content Management" tab has dissapeared. The missing "Create Content" would normally be under "Content Management."

How can I recover it? (I'm using Drupal 7).

Help much appreciated. Thanks.

# Answer
> 1 votes
It looks like you're using admin menu, right? A blog post about rebuilding the drupal admin menu says you can:

* Delete you current links via SQL `DELETE FROM menu_links WHERE menu_name='management'`.
* Clear all caches at Administration \> Configuration \> Development (or just: http://example.com/admin/config/development/performance if your menu is ruined at this point). Drush users can of curse use drush cc all or even drush cc menu

Disclaimer, I didn't try it myself. Hope this helps.

# Answer
> 0 votes
Thanks! **I was able to figure it out!**

I clicked:

* site building
* menus
* list menus
* navigation \[www.yourwebsite.com/ admin/build/menu-customize/navigation\]
* create content \[www.yourwebsite.com/node/add\]

I can go in and create content, even though it's not listed in my Drupal admin panel. Next step is to figure out how to move it back to it's proper place in the admin panel. But at least I can create content now.

---
Tags: 7
---


# Question
Title: how to get the values from views in page template
I created a view (page name 'Archives') to load the following values from all the posts of a particular content type.
Year = field\_year
Volume = field\_volume
Issue = field\_issue
By using views I couldn't get the desired output. So, I created a template file (views-view--archives--page.tpl.php) and wrote the following code. Please see the attached screenshot & code below. Please help me in correcting the code. This would be a great help. Thanks

```
<ul>
 <?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
  <li>
    <span class="view-header"><?php print $item['field_year']." (volume - ".$item['field_volume'].")"; ?></span>
    <span class="view-issues"><?php print "Issue ".$item['field_issue']; ?></span>
  </li>
 <?php endforeach; ?>
</ul>

```

# Answer
> 1 votes
You should use the Views templates (under Advanced \> Other \> Theme: Information). It gives several output types. When you create a Views specific template file, it passes a whole bunch of variable/values that you have chosen in your Views to the Views template file. Then you are free to use it like how you want. Read more info at http://views-help.doc.logrus.com/help/views/analyze-theme

# Answer
> 0 votes
You shouldn't need to write a template. This can be done in the views UI.

Click on the year field and select Exclude from display. Then click the volume field and override the output. Using replacement patterns it should be something like \[field\_year\] \[field\_volume\]. Then click settings for your display and select Group by field\_volume.

See https://drupal.org/node/1565480

---
Tags: views, entities, theming
---


# Question
Title: How do you get Solr Views to query Acquia Search?
I'm looking to build a set of sites which are all indexed by Acquia Search into a single index.

I also plan to build an umbrella site to help people discover content on the sites below. I was looking to the Apace Solr Views module for this. How do I get this module to build views from the Acquia Search index?

# Answer
> 0 votes
**Acquia search :**

A search service provided by acquia which in-turns uses the Apache Solr search inside. Currently they are updated their acquia search with Solr 3.5.

**Apace Solr Views module :** Module when enabled converts the views query from a database query to apache solr search query.

While enabling the Apache Solr Views module it will look for the apache solr configured in the drupal system automatically.

---
Tags: views, search
---


# Question
Title: Adding prefix and suffix to a content type field
Is there a way to add content to a content type's field in a mechanized way? Say for instance I have a field for how many servings a recipe is going to make but I don't want my user to have to write "Makes" and "Servings." over and over again and risk spelling something wrong.

Is there a way to make it so all she needs is a number field and I can automagically make it say "Makes" \[number\] "servings."

Perhaps there is a hook or module that I can use?

# Answer
You can add prefix and suffix in the display settings of the field with the Simple Field Formatter module

1. Download and enable the module
2. Go to admin/structure/types/manage/mycontenttype/display
3. Click on the settings icon for the specific field
> 1 votes

---
Tags: entities, nodes
---


title: Assign User Permissions to a File?

text:
# Question
Title: Assign User Permissions to a File?
My scenario is as follows:

I'd like to create 2 node types "public file" and "private file". Each node type has the file field for file uploads. I would like the ability to assign user permissions to any file that is uploaded to the private node type. The users would be managed through the Drupal User module.

Thanks in advance!

# Answer
> 0 votes
The closest out-of-the-box option is to use a combination of the public (public://) and private (private://) file system. Public files can be access by anyone with a url to the file. They're served directly from the server without really having to deal with drupal. Private files on the other hand require the user to log in.

The downside to the private file system is the files are basically streamed to the end user via php which is slower. There are ways around this but if you're not expecting heavy download traffic then I wouldn't worry about it just yet.

The way access control is handled is via the node. You can create a single filefield and attach it to a any content type. Let's just say we're using the 'article' content type for now with a single filefield that supports both public and private storage. When you add a file to the article you can choose the private file system. You can then use any of the node access control modules (tac\_lite, og, etc.) to control who can see the node. Those that can see the node can then download the file.

---
Tags: users, files
---


# Question
Title: Enable storing of taxonomy term name instead of ID in views filter criteria
**Background**
I use Features module to deploy the code to my stagging. For e.g. I have a feature which exports:

* content type - *Player*
* Taxonomy term on this content type of vocab - *Medals*
* View which lists the *Player* with filter type: `Content: Has taxonomy term (=gold)`

*Medals* has three terms - *gold*, *silver*, and *bronze*.
In the feature the vocabulary is being exported while the terms are not. I need to add the terms manually again on the server.

**Problem**
The feature exports the term id of the term instead of the name (tid : 1). So, when I enable the feature on the stagging server, and if the term name for `tid : 1` is silver. The views filter criteria is changed and it is conflicting with the use case.
I was just wondering if there is a way to export the views taxonomy filter name instead of id?

# Answer
> 1 votes
I couldn't find a solution for filtering via term name. However, I came up with a workaround where I was able to featurize the taxonomy terms too.
I'm using UUID Features Integration for the same:

> The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.

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


# Question
Title: Show node for specific content type using views contextual filter
Let me explain the issue in detail. I have created two views. The first view displays listing of content for content type named Invoice. The View has a page display. This view is working fine.

I want when a user clicks on any content item the resulting page should use the another view which I have created to show the items for a specific content item based on the node id passed.

How to pass the node id as a contextual filter for second view. I have given the path for second view as node/%, but then the view just work for all content types. I don't want that thing to happen. I just wants to have that view called for Invoice content type items.

I have also used validation criteria for contextual filter, but that doesn't work.

# Answer
> 1 votes
A simple query alter will do the job.

Say example you are using a module my\_views\_invoice

```
    function my_views_invoice_views_query_alter(&$view, &$query) {

    $nodeid = $view->args[0][1]; // get the node id from contextual filters. Ex :Array ( [0] => node [1] => 1 )

   $content_type =  node_load($nodeid) ;// get the content type from the node load : Ex $content_type->type

      if ($view->name == '<Your view name>') {
// Add a where condition in the query like below..

        foreach ($query->where[0]['conditions'] as $key => $conditions) {
          if ($conditions['field'] == 'node.type') {
            $query->where[0]['conditions'][$key]['type'] = $content_type->type;

          }
        }
    }

```

---
Tags: nodes, views
---


# Question
Title: Error in drupal_form_submit when taxonomy reference (tid) is set
While trying to creating a node programmatically using 'drupal\_form\_submit' i've come across a php error in the form.inc code

Here's my code

```
function vl_sample_data_generate_yvbct1() {

  module_load_include('inc', 'node', 'node.pages');

  global $user;

  $content = 'Generating YVB CT1';
  $form_state = array();
  $data = array();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => $user->name,
    'type' => 'yvb_ct1',
    'language' => LANGUAGE_NONE,
  );
  node_object_prepare($node);

  $data['uid'] = $user->uid;
  $data['created'] = time();
  $data['type'] = 'yvb_ct1';
  $data['language'] = LANGUAGE_NONE;
  $data['title'] = 'Node created on ' . time();
  $data['status'] = 1;
  $data['op'] = 'Save';

  $data['field_middle_name'][LANGUAGE_NONE][0]['value'] = 'Alex';
  $data['field_gender'][LANGUAGE_NONE][0]['tid'] = 24;

  $form_state['values'] = $data;

  drupal_form_submit('yvb_ct1_node_form', $form_state, $node);

  return $content;
}

```

The error i get when i run the function (as a menu callback) is

```
Warning: Illegal offset type in isset or empty in _form_validate() (line 1333 of /opt/httpd/htdocs/www/staging/jns/trunk/includes/form.inc).
An illegal choice has been detected. Please contact the site administrator.

Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /opt/httpd/htdocs/www/staging/jns/trunk/includes/entity.inc).

Warning: Illegal offset type in taxonomy_field_validate() (line 1519 of /opt/httpd/htdocs/www/staging/jns/trunk/modules/taxonomy/taxonomy.module).

Notice: Trying to get property of non-object in taxonomy_field_validate() (line 1519 of /opt/httpd/htdocs/www/staging/jns/trunk/modules/taxonomy/taxonomy.module).

```

However, if i comment out the line

```
  $data['field_gender'][LANGUAGE_NONE][0]['tid'] = 24;

```

It works fine. Am using Drupal 7.26. Also, the term tid does exist and belongs to the valid Vocabulary which is assigned in the content type.

Any help regarding the above problem is appreciated.

Thanks

Yashesh

# Answer
It is possible that 24 is not a valid taxonomy term ID in the system, but I'm not sure if that's it. So I would check that using `taxonomy_get_term_by_name` or something. Also, and perhaps first, make sure to verify the field\_gender field exists, as it might not *always* be there in the system and you don't want nasty bugs down the road.

```
// Check if field_gender field exists for node type yvb_ct1
$field_instances = field_info_instance('node', 'field_gender', 'yvb_ct1');
if (isset($field_instances['field_gender'])) :

  // Now check if the taxonomy ID is correct
  // I assume you are looking for a term name of 'female'
  if (!empty(taxonomy_get_term_by_name('female', 'gender')))
    // now try setting term reference field value

endif;

```

This is untested but I hope it might help get you closer.
> 1 votes

# Answer
```
// For autocomplete term reference fields
$tax = taxonomy_term_load(4)->name;
$data['field_test_tax'][LANGUAGE_NONE] = $tax;

//For widgets select list or radio buttons term reference fields
$data['field_gender_tax'][LANGUAGE_NONE] = 8; //tid value
$data['field_gender_tax_radio'][LANGUAGE_NONE] = 11; //tid value

```
> 0 votes

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


title: Custom Logout and Drupal Logout

text:
# Question
Title: Custom Logout and Drupal Logout
we are implementing a custom login (based on an auth cookie given by a third party authentication service). When the cookie arrives, we trigger the drupal user\_login. When the user logs out (via a custom box, NOT drupal logout link), we trigger the user\_logout.

The problem is: if you clear the cookie auth, you remain logged on drupal. What hook can we implement to trigger the logout anytime the cookie auth disappear?

# Answer
There is no hook for 3rd party cookie removal, and there cannot be. You need to bootstrap Drupal and call `user_logout()`.

You could also use `hook_boot()` to test for the cookie and logout if it's not there, but it is a **bad idea** \- it may seriously hurt your performance and will not play nice with external caches.
> 2 votes

---
Tags: users
---


title: Drush on windows - back up goes missing

text:
# Question
Title: Drush on windows - back up goes missing
I am new to drupal and drush, so please do not close this if it's naive.

My setup:

* Windows 7
* Xampp 1.8.3 (PHP 5.5.6/Apache 2.4.7/PHP 5.5.6)
* Drupal 7.26
* Drush 6.3-dev

Intention:

Back up my site and restore on a separate machine using `drush
 archive-dump` and `drush archive-restore`

Action: I went into the folder where I have installed drupal and issued the command `drush archive-dump`

Result:

```
Archive saved to                                                            [ok]

C:\Users\srihari.sahu/drush-backups/archive-dump/20140206101025/drup
al.20140206_101027.tar.gz
C:\Users\srihari.sahu/drush-backups/archive-dump/20140206101025/drup
al.20140206_101027.tar.gz

```

When I go in the folder `C:\Users\srihari.sahu\drush-backups\archive-dump\20140206101025\` I don't see anything. The folder is blank.

What am I missing?

# Answer
> 0 votes
This is a known issue for drush in Windows, along with several others regarding sql operations and rsync. The best solution I know so far is described in:

https://drupal.org/node/1393672

---
Tags: drush, backups
---


title: View in a list Machine Names

text:
# Question
Title: View in a list Machine Names
I am new to Drupal7, and working on a site with different users.

And my probably I am currently encountering is when whenever someone creates a content, field, etc. It generates a machine name.

Using Drupal, it automatically generates one based on the given title of node. But it won't be saved if the machine name already exist.

Is there anyway to know what machine names exist? And to which this machine name is assigned?

# Answer
For some "object" there is.

* on admin/reports/fields you find a list of every field, with type and machine name
* on admin/structure/types you find a list of every content type, wth machine name

and so on for views, rules and any other "object".

If you need a "report" you could use Views, o make a directly a query.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Ensure atomicity of user_save within hook_node_delete
In my system, a user has a number of bookings (nodes of content type 'booking') associated. Each of these bookings has a 'field\_price' field and a 'field\_customer\_user' field (for which I am using the Entity Reference module) that links the booking to its customer. The user also has a 'field\_bill' field containing the sum of all his bookings' prices.

Each time a booking gets deleted, I want to subtract its price from its user's bill. I'm doing it the following way, using hook\_node\_delete:

```
function mysite_node_delete($node) {
   if ($node->type == 'booking') {
     if ($account = user_load($node->field_customer_user[LANGUAGE_NONE][0]['target_id'])) {
       $bill = $account->field_bill[LANGUAGE_NONE][0]['value'];
       $bill -= $node->field_price[LANGUAGE_NONE][0]['value'];
       $account->field_bill[LANGUAGE_NONE][0]['value'] = $bill;
       user_save($account);
     }
   }
}

```

However, sometimes this does not work as expected. Given the following case:

> User booking #1: 100$
>
> User booking #2: 200$
>
> User booking #3: 50$
>
> Total bill: 350$

An administrator logs in and deletes all three bookings for this user sequentially, starting from booking #1 and finishing with booking #3. The user's total bill should be 0 now, but it ends up being

> Total bill: 300$.

I guess that this means that when user\_save($account) was called for booking #3, the user bill had not been properly updated by the first two calls to hook\_node\_delete. Therefore, the old value (350$) gets fetched and subtracted the price of booking #3, and end ups being 300$, which is not correct.

Is there anyway of making it work?

# Answer
`user_save()` itself is likely to be guaranteed atomic. You're running innodb or equivalent, right?

However, you have no guarantees that the user isn't altered between your `user_load()` and `user_save()`, which can cause a race condition. There lock.inc for that.

> A database-mediated implementation of a locking mechanism.

This is very unlikely though, and if this happens to you often and regularly, you likely have a problem elsewhere in your code.

However, not even that can protect you from other parts of the code, in a parallel request, loading up the user, modifying it, and saving it back, in between your calls. For better or worse, you can't reasonably guarantee that no other piece of code, such as contributed modules, modifies your users.

Suggested options:

1. Modify the field value directly like `UPDATE [table] SET [field] = [field] +/- [value]`. Then you can rely on the DB's underlying mechanisms for atomicity.
2. Accept a small risk of failure. Run a hourly cron job to recalculate values, correcting for mistakes.
3. Don't use a user field for this data. Either use a custom entity, or directly manage a custom table. Force all updates through a lock mechanism.
> 3 votes

---
Tags: 7, hooks, users
---


title: Custom form with custom submit

text:
# Question
Title: Custom form with custom submit
I'm building a custom form that will show some details from a web service.

On my page callback I have two fields and submit button:

```
<?php

$form['starting_date'] = array(
   '#type' => 'date_popup',
   '#title' => 'Starting date',
   '#date_format' => 'd.m.Y',
);

$form['end_date'] = array(
   '#type' => 'date_popup',
   '#title' => 'End date',
   '#date_format' => 'd.m.Y',
);

$form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Check'),
   '#submit' => array('reports_list'),
);

```

On

```
<?php
function reports_list($form, &$form_state) {

}

```

I'm inserting the code that connects with the web service, passing the form\_state values of selected dates and after that I'm trying to display the table with the web service details on the same page, but after clicking on submit it simply refresh the page and doesn't show anything.

I can see connecting with the web service is successful.

On custom submit function this for an example is not displaying:

```
<?php

$form['results'] = array(
   '#type' => 'markup',
   '#markup' => '<p>TEST</p>',
);

```

I'm doing something wrong, I guess...

EDIT: I've tried to display something in the submit function like this:

```
<?php

$form['results'] = array(
   '#type' => 'markup',
   'markup' => 'TEST10',
);

echo render($form['results']);

```

It's not working.

# Answer
I think your problem is due to a misunderstanding of how Drupal forms work.

Drupal uses the PRG pattern for form submissions. That means for you, that you can't set form elements in the submit handler.

You can either set a message using `drupal_set_message()` which will be displayed on the next page.

Or you can instruct the form to rebuild, which will result in a redirect to the same form page that you came from with your form builder being called again. In the form builder function you can then check if the form has previously been submitted and then build the form accordingly. This second option is usually referred to as a multistep form. Have a look at this blog post for an example: http://davidsonj.com/blog/how-create-multi-step-form-drupal-7
> 2 votes

---
Tags: forms
---


title: Displaying User Profile page externally

text:
# Question
Title: Displaying User Profile page externally
I have a custom page(Ex:usertest.php) in root folder and externally loaded drupal. If I print $user-\>uid it is displaying the user id. Upto now it is fine. But if I included the user-profile.tpl.php which exists in core "modules/user" folder, it is not working. From below code, it is not going to if loop. menu\_get\_object('user') is not wokring here. Any suggestions..

```
if($account = menu_get_object('user')) {
    echo "User Profile Page";
}

```

# Code

```
<?php
global $user;
define('DRUPAL_ROOT',  '/var/www/sitename/doctors');
$drupal_url  = 'http://sitename/doctors'; // no trailing slashes
drupal_external_load($drupal_path, $drupal_url);
echo $uid = $user->uid;

/**************************************  Start - External Login related functions *********************************/
// load drupal stuff
function drupal_external_load($drupal_url) {
  global $base_url;

  // set drupal base_url (if not set set in settings.php)
  // because it's used in session name
  $base_url = $drupal_url;

  // save current path
  $current_path = getcwd();

  // move to drupal path, because it uses relative path for its includes
  chdir(DRUPAL_ROOT);

  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  // to use the drupal global user var (instead of session hack)
  // drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

  // return the current path
  chdir($current_path);
}

// load a drupal user into the user obj
function drupal_external_userload($user_info = array()) {
  // Dynamically compose a SQL query:
  $query = array();
  $params = array();

  if (is_numeric($user_info)) {
    $user_info = array('uid' => $user_info);
  }
  elseif (!is_array($user_info)) {
    return FALSE;
  }

  foreach ($user_info as $key => $value) {
    if ($key == 'uid' || $key == 'status') {
      $query[] = "$key = %d";
      $params[] = $value;
    }
    else if ($key == 'pass') {
      $query[] = "pass = '%s'";
      $params[] = md5($value);
    }
    else {
      $query[]= "LOWER($key) = LOWER('%s')";
      $params[] = $value;
    }
  }
  $result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);

  if ($user = db_fetch_object($result)) {
    $user = drupal_unpack($user);

    $user->roles = array();
    if ($user->uid) {
      $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    }
    else {
      $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
    }
    $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
    while ($role = db_fetch_object($result)) {
      $user->roles[$role->rid] = $role->name;
    }
    //user_module_invoke('load', $user_info, $user);
  }
  else {
    $user = FALSE;
  }

  return $user;
}

// don't send any headers before calling this
function drupal_external_login($username, $password) {
  global $user;

  if ( $user->uid > 0 ) {
    if ( $user->name != $username ) {
      drupal_external_logout();
    } else {
      return true;
    }
  }

  require DRUPAL_ROOT. '/includes/password.inc' ;
  $account = user_load_by_name($username);
  if ( user_check_password($password, $account) ) {
    $user = $account;
    drupal_session_regenerate();
    return true;
  }

  return false;
}

function drupal_external_logout() {
  global $user;
  session_destroy();
  $user = drupal_anonymous_user();
}

/**************************************  Start - External Login related functions *********************************/
?>

```

# Answer
> 1 votes
If you only want to load the user object, then I would suggest using `user_load()`.

To stay in your logic with `menu_get_object()`, I guess this fails, because you omit the third argument which sets the path, see the doc. If the path is not given it will default to the current request path which is probably not containing the users id in your case?! Try this:

```
menu_get_object('user', 1, 'user/' . $user->uid);

```

But this will result in the same as calling `user_load()`.

In order to use user.module funcitonality, which I guess is what you want, you could try to fake the request by manipulating $\_GET, but even if that works, it's afaik considered bad practice.

---
Tags: users
---


title: Nested Taxonomies

text:
# Question
Title: Nested Taxonomies
I am trying to build a site with this kind of taxonomy.

This is just an example, not the actual nodes:

```
Level 1 > Level 1-a > Level 1-a-i
Level 1 > Level 1-a > Level 1-a-ii
Level 1 > Level 1-b > Level 1-b-iv
Level 2 > LEvel 2-a > LEvel 2-a-x

```

But using the Taxonomy module, I am only allowed to create

```
Level 1 > Level 1-a
Level 1 > Level 1-b
Level 2 > Level 2-a

```

Is there anyway that I can create deeper nested taxonomy using the Taxonomy module?

# Answer
Is the following screen respond to your needs?

If this screen is what you want, you just need to drag and drop term in admin UI...
> 4 votes

---
Tags: taxonomy-terms
---


# Question
Title: colorbox not working with ajax framework
I am using D7 ajax framework. I have created a link which loads a node in a div by click. But colorbox doesn't work on these nodes. Images has a class colorbox but not the rest like colorbox-init etc.

# Answer
> 0 votes
According to the colorbox module documentation,

> **Load content in a Colorbox**
>
> Check the "Enable Colorbox load" option in Colorbox settings. This enables custom links that can open content in a Colorbox. Add the class "colorbox-load" to the link and build the url like this "\[path\]?width=500&height=500&iframe=true" or "\[path\]?width=500&height=500" if you don't want an iframe.
>
> Other modules may activate this for easy Colorbox integration.

First, you have to check Colorbox configuration

Then, you need to edit your view to add custom class to your link. Ajax link may not be required in your case, because Colorbox module will open your content with it's own manner...

But I can't test this point, so check with and without and edit this answer :).

**Links**

Documentation page

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


# Question
Title: "Trying to get property of non-object" for image_get_info
I have the following code:

```
  $imageinfo = image_get_info($newfile->uri, $toolkit = FALSE);

  $newrecord = array(
     blah blah blah
     'width' => $imageinfo->width,
     'height' => $imageinfo->height
    );

```

The width and height lines get the "Trying to get property of non-object" error.

If I print the contents of the `$imageinfo` array, it's this:

```
Array
(
    [width] => 630
    [height] => 315
    [extension] => jpg
    [mime_type] => image/jpeg
    [file_size] => 30334
)

```

I must be doing something stupid here. What is it?

# Answer
Always, always read the documentation first:

> **Return Value**
>
> FALSE, if the file could not be found or is not an image. Otherwise, **a keyed array** containing information about the image:

Emphasis mine.
> 1 votes

---
Tags: media
---


title: Pagination isn't working

text:
# Question
Title: Pagination isn't working
I have a homepage view called FrontPage. Currently, it shows the pagination link like "1, 2, 3 Next-\>" as it should; when I click on *Next*, it goes to http://example.com, not http://example.com/page/1/0.

I have checked the taxonomy archive, and it is has the same problem. The same is true for the Blog posts.

I checked pager.inc, but I don't see any problem. I haven't hooked anything in template.php.

Why is the *Next* link pointing to the wrong page, and what could I do to fix it?

# Answer
> 0 votes
Including your versions of Drupal core and Views module might be helpful.

Any chance you're using the Global Redirect module? I had the same problem when I took a dev site live (Drupal 7.26, Views 7.x-3.7 and 7.x-3.7+22-dev, Global Redirect 7.x-1.5), and this patch in globalredirect.module addressed the issue.

https://drupal.org/node/1789546

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


# Question
Title: drupal Theme class is missing, I guess! How to fix it?
I am using civicrm on drupal 7.26. When I use default theme i can see the link "View all Contribution...." but as you can see from top part of screenshot it does not appear on bootstrap theme. can anyone help me to fix this please? thanks

# Answer
> 0 votes
Make sure your theme has all the appropriate Theme Regions (more details about Theme Regions). Also, there may be some custom PHP overrides provided by the working theme, so you'll want to review the theme's `template.php` file for any custom PHP theme overrides you may want to help bring over to your other theme.

---
Tags: theming
---


# Question
Title: How to use hook_form_alter with commerce checkout
The module "commerce\_checkout\_buttons" alters the buttons in the commerce checkout process as seen below in using HOOK\_form\_alter. In this code, only the review form is being altered, but the changes seem to be global in the checkout process?

For example, the site I'm working with has a one-page checkout, and the Review pane doesn't include anything. Yet, the buttons are altered.

Can anyone explain how this works?

```
function commerce_checkout_buttons_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
    case 'commerce_checkout_form_shipping':
    case 'commerce_checkout_form_review':
      if (isset($form['buttons']['back']['#value'])) {
        $form['buttons']['back']['#value'] = t('Back');
      }
      if (isset($form['buttons']['continue']['#value'])) {
        $form['buttons']['continue']['#value'] = t('Continue');
      }
      if (isset($form['buttons']['back']['#prefix'])) {
        unset($form['buttons']['back']['#prefix']);
      }
      if (isset($form['buttons']['cancel']['#prefix'])) {
        unset($form['buttons']['cancel']['#prefix']);
      }
      break;
  }
}

```

# Answer
If you remove the code shown below, it would only affect the review pane.

```
case 'commerce_checkout_form_checkout':
    break;
case 'commerce_checkout_form_shipping':
    break;

```
> 2 votes

# Answer
The problem was me not properly understanding how fallthrough works in PHP's switch statement.

Without break statements, once a case statement is found with a value that matches the value of the switch expression, PHP will continue to execute the statements until the end of the switch block.

In this case, the match occurs with form\_id 'commerce\_checkout\_form\_checkout' and PHP executes all statements under 'commerce\_checkout\_form\_review'. So, effectively, this code alters checkout buttons by matching all three of the form\_ids listed.
> 2 votes

---
Tags: commerce
---


# Question
Title: How would I add a class with the same name as the header?
I'd like to add a class with the same name as the header, in order to keep similar header columns the same size. Basically, the code is generating multiple tables, some of which have the same header items, and some of which do not. All columns with the same header value will take the exact same styling.

```
$string .= theme('table', array('header' => array_values($headers[$group]), 'rows' => $results));

```

$string is '' at the beginning of this, and I want to add the class to the values in $header - so ideally it would look like this:

```
<th class="Header">Header</th>

```

# Answer
You'll want to consider doing this in PHP, by overriding the theme/output markup for each Table Header, specifically using the theme\_table() override function to add a `class` attribute to each table header argument.

## Simplified code sample

```
$table_headers = array(
      array(
        'class' => array($node->title), // Adds 'class' HTML attribute.
      ),
      // More code goes here to define the table headers...
    );

```
> 0 votes

---
Tags: 7, theming
---