# Question
Title: How to add a tpl file to a block from a custom module
I have a custom module that build a block. I'm trying to add a tpl file, but I don't get nothing. This is my code:

```
<?php
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function tados2_block_info() {
  $blocks = array();

  $blocks['block_with_tpl'] = array(
    // info: The name of the block.
    'info' => t('Tados2 example: block with tpl'),
    'status' => TRUE,
  );

  return $blocks;
}
/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function tados2_block_view($delta = '') {
  switch ($delta) {
    case'block_with_tpl':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Tados2 block with tpl');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = t('Hola mundo');//_tados2_block_with_tpl_contents();
    break;
  }
  return $block;
}
?>

```

I'm trying to move the content to a tpl.php file.

This what I'm trying:

```
<?php
/**
 *
 * Implementen hook_theme
 *
 */
function tados2_theme(){
  return array(
    'tados2_block' => array(
      //'render element' => 'elements',
      'template' => 'tados2_block',
      'variables' => array('title' => NULL, 'content' => NULL),
    ),
  );
}
/**
 * preprocess function
 *
 */
function template_preprocess_tados2_block(&$variables) {
  dpm($variables);
}
?>

```

# Answer
You have to call your theming function:

```
$block['content'] = theme('tados2_block', array('title' => 'foo', 'content' => 'bar'));

```
> 3 votes

# Answer
I have tried to use a template file in my block. This is my solution.

* Fist step: You need to register your theme. Use the following code in yourmodule.module.

```
function yourmodule_theme($existing, $type, $theme, $path){
  return array(
    'yourmodule_block' => array(
      'template' => 'yourmodule',
      'variables'=> array('var1' => NULL, 'var2' => NULL),
    ),
  );
}

```

Note that in `'template' => 'yourmodule'` 'yourmodule' is the template filename in your module folder.
Check hook\_theme() for more details.
* Secondnd step: Use your theme for a block.

```
function yourmodule_block_view($delta = '') {
  switch ($delta) {
    case 'yourmodule_block':
      $block['subject'] = 'LinhNH-Training';
      $block['content']['yourmodule'] = array(
        '#theme' => 'yourmodule_block',
        '#var1' => 'Module Title',
        '#var2'=>'Content '
      );

      return $block;
      break;
  }

  // return $block;
}

```
> 3 votes

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


# Question
Title: View Template Override that is full page
I need to create a template for a view i've created (which I know how to do) but I don't want the page to be wrapped in the drupal html.php code. I want the resulting page to be only what is in the template file I create.

How do I do this? I looked online for examples but coudn't find anything.

Thanks C

EDIT:

I found this which does what I need for content types `lab`

```
function yourthemename_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    if($node->type == "lab") {
      $vars['theme_hook_suggestions'][] = 'html__lab';
    }
  }
}

```

Then created a file called: html--lab.tpl.php

Can this method be used for me view? does it have to be `if($node->type == "lab")`? can I use something like `if($view == "viewname")`

Thanks

# Answer
> 0 votes
Got the answer elsewhere... posting it here.

Added the follwoing to my `template.php` file:

```
function yourthemename_preprocess_html(&$vars) {
  if (arg(0) == 'mypage') {
    $vars['theme_hook_suggestions'][] = 'html__mypage';
  }
}
function yourthemename_preprocess_page(&$vars) {
  if (arg(0) == 'mypage') {
    $vars['theme_hook_suggestions'][] = 'page__mypage';
  }
}

```

Then created the following files:

```
html--mypage.tpl.php

page--mypage.tpl.php

```

Works perfectly and simple to do.

Thanks goes to @Ionut.A and @Clive

Cheers C

# Answer
> 3 votes
If you want views template not to be wrapped in html.tpl.php, page.tpl.php and any other template whatsoever, I would susggest to do the following:

```
function YOUR_MODULE_menu(){
    $items = array();
    $items['path/you/want/your/view/to/be/available/at'] = array(
        'type' => MENU_NORMAL_ITEM,
        'title' => 'View without wrapping templates',
        'page callback' => 'your_function_name',
        'access callback' => TRUE,
    );
    return $items;
}

function your_function_name() {
    print views_embed_view('your_view_name', 'your_display_name');
    exit;
}

```

# Answer
> 1 votes
you should create sub-theme and override `html.tpl.php` and `page.tpl.php` as your desire

then using themekey module to set your sub-them for pages which need it

---
Tags: views, theming
---


# Question
Title: Caching mysql results in cache table to be retrieved later
How can i fetch records from mysql results stored in cache table ?

```
$cached_res_obj = cache_get("expensive_sql", MY_CACHE_TABLE);
$res            = $cached_res_obj->data;
while ($row = db_fetch_array($res)) {
    print_r($row);
}
die(__FUNCTION__);

```

I dont get any results. If i run the actual query through drupal I get results. What should be done here ?

# Answer
You can't store the query result resource directly in the cache table as it can't be serialised. Instead you should loop through that resource when you first run the expensive query, and cache an array of results, like so:

```
$q = db_query('expensive sql here');
$data = array();
while ($row = db_fetch_object($q)) {
  $data[] = $row;
}

cache_set('expensive_sql', $data, MY_CACHE_TABLE);

```

Then when you pick it up at the other end you can just loop through that array:

```
$cached_res_obj = cache_get("expensive_sql", MY_CACHE_TABLE);
$res            = $cached_res_obj->data;

foreach ($res as $row) {
  print_r($row);
}

```
> 3 votes

---
Tags: 6, caching, database
---


# Question
Title: Why is the "Recent log entries" report missing?
I have a weird problem. I have the same website on two servers, live and staging, and on one server I can access the "Recent log entries" page, but on the other one, it doesn't exists.

On `admin/reports/settings`, the "Enable access log" is enabled, but the page `admin/reports/dblog` shows the same page as `admin/reports`

Any ideas what might be causing this?

# Answer
> 0 votes
It was overridden in code by the previous programmer x(

# Answer
> 3 votes
Check to make sure you have the module "Database logging" turned on.

THis is sometimes turned off for performance reasons.

---
Tags: 6, log-messages
---


title: call to undefined fucntion error

text:
# Question
Title: call to undefined fucntion error
Call to undefined function modalframe\_close\_dialog() in

I am using Drupal 7

```
function close_model_dialog($form, &$form_state) {
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();
  $form_state['redirect'] = FALSE;
  modalframe_close_dialog();
  modalframe_child_js();
}

```

# Answer
> 2 votes
It means what it says: There is no file included in the current page request that contains the definition for a function called `modalframe_close_dialog()`.

A quick Google search shows that this function is part of the `ModalFrame API` module, for which there is only a Drupal 6 release (not Drupal 7). I guess you've copied this code from a Drupal 6 site without changing it?

The comments on the ModalFrame API module page say:

> It seems this feature is being included in Drupal core itself. So, probably there will be no stable release of this module for Drupal 7 because it will be already there

My best guess is that the Drupal 7 equivalent of this function is `overlay_close_dialog()`, but I can't comment as to whether that will work as in a drop-in replacement for you current code.

It might be worth reading the Initial D7UX admin overlay thread, it's basically the discussion about moving ModalFrame API into core.

---
Tags: chaos-tool-suite
---


# Question
Title: The custom node template file is not working
I've created template file named node--product-display.tpl.php as suggested by the Theme developer module, but the changes I made to this file don't show up.
I've also copied the node.tpl.php file in my templates directory. The changes in the latter one show up but that in the former one doesn't.

Do you have any suggestion?

I have cleared the cache. The template file is for a "Product Display" content type, whose machine name is "product\_display."

# Answer
Try node--product\_display.tpl.php.

If your file is empty, it will show the default template file; make sure you have write something in your custom file.

Be sure to clear the cache.
> 6 votes

---
Tags: nodes
---


# Question
Title: How to filter an already rendered calendar view of a specific date with categories (taxonomy terms)?
I'm using the latest dev-versions of date/views/calendar/ctools to create an event calendar to display a variety of different events. These events are created with a content-type "event" and classified by a vocabulary (e.g. "movie" or "sport").

I have an already working block of the calendar (showing the current month by default and linking to the corresponding date). If i click on a date i have a list of every event on that date.

How can i reduce the results of that list through the taxonomy terms (movie, sport)?

Any hint or solution is very appreciated...

# Answer
If your "list of every event on that date" is generated by Views, you can add a Filter to Views based on Taxonomy Term. This can then either be exposed to the user so they can pick Movie or Sport - or you can select which one you want explicitly for them.

See selection options below - you'd likely want "Taxonomy: Term" (and you'd be doing this in the Filter - not Contextual Filter).
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to add a second Contextual Filter to the calendar view? (this view is automatically created by the calendar module)?
I have enabled the calendar module which generate a new view called **calendar**.

The calendar view has a page called **month** with just one **contextual filter**. It works fine.

The problem is that I to added a second **contextual filter**.This is what I've done:

* The content type that this view page shows is: "actividades".
* This content type has the field **"poblacion"** of the type (term reference).

Then in the view:

* I added a Relationship: **Content: Taxonomy terms on node**
* I added the Contextual Filter :**(term form Poblaciones) Taxonomy term: Name** .

But it's not working at all. I think I need to modify the path of this view page which at the moment is: actividades/month. But I don't know how...

If I go to the url: actividades/month/barcelona it doesn't work even though I have a node tagged with this term. I guess this happens because the first argument is for the date, here is where I get lost

# Answer
What are you trying to achieve exactly? You want to restrict the calender to show only nodes tagged with a certain term?

It looks like you're trying to do this by setting up a relationship with the terms and then passing in the term name. Is there a reason why you're not using the Content: Has taxonomy term ID contextual filter? This cuts out the need for the relationship, but requires you to pass a term ID rather than a term name.

If there is a reason why you're not doing this, then ignore me :) Just thought I'd reply in case you didn't know about it.
> 1 votes

---
Tags: datetime
---


# Question
Title: Add microdata to breadcrumbs - Some trouble with hooks
I'm trying to add microdata to the breadcrumbs. I found on the web this fix which I tried to include to my own SEO module like this:

```
function mymod_page_alter(&$variables) {
    if (!isset($variables['breadcrumb'])) {
        $variables['breadcrumb'] = theme('my_microdata', array('breadcrumb' => drupal_get_breadcrumb()));
    }
}
function mymod_theme($existing, $type, $theme, $path) {
  return array(
    'my_microdata' => array(
     'variables' => array('breadcrumb' =>array()),
    ),
  );
}
function mymod_menu_breadcrumb_alter(&$active_trail, $item){
  foreach($active_trail as $id=>$active_trail_item){
    $active_trail[$id]['localized_options']['attributes']['itemprop'][]="url";
  }
}
function theme_my_microdata($variables){
 $breadcrumb=$variables['breadcrumb'];
print_r(debug_backtrace());
 $output="*+*+*+*+*";
  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
    $output .= '<div class="breadcrumb">';
    $separator="";
    foreach($breadcrumb as $breadcrumb_item){
      $output.='<span typeof="datav:Breadcrumb">'.$separator.$breadcrumb_item."</span>";
      $separator="»";
    }
    $output .='</div>';
  }

    return $output."xXxXxXx";
}

```

So far I checked that all this code is executed. But this theming is not applied on my page. Why does my code not work? Could this been related with the module `breadcrumb`? I know that this output will be garbage but I cannot see the result.

If I guess right than is the output created by *theme.inc* line 1682ff `theme_breadcrumb(...)`instead of my code. How can I change that?

---

I just found the theme\_breadcrumbs there is shown in their solution this line:

```
function YOURTHEME_breadcrumb($variables) {

```

Well can *YOURTHEME* my module name or have I to build a theme?

# Answer
> 1 votes
Your implementation of hook\_page\_alter() doesn't work because the parameter passed to the hook (`$page`) doesn't contain `$page['breadcrumb']`.

I used the following code to verify the content of the parameter passed as argument.

```
$path = 'node/14';

if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    if ($router_item['include_file']) {
      require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
    }
    $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  }
}

$main_content_display = &drupal_static('system_main_content_added', FALSE);

if (is_string($page_callback_result) || (is_array($page_callback_result) && (!isset($page_callback_result['#type']) || ($page_callback_result['#type'] != 'page')))) {
  drupal_set_page_content($page_callback_result);
  $page_callback_result = element_info('page');
}

foreach (module_implements('page_build') as $module) {
  $function = $module . '_page_build';
  $function($page_callback_result);
}

drupal_alter('page', $page_callback_result);

if (!$main_content_display) {
  $page_callback_result['content']['system_main'] = drupal_set_page_content();
}

dsm($page_callback_result);

```

"node/14" is the path for an "Article" node I have on my test site.
The code has been created looking at the code of different Drupal functions: drupal\_deliver\_html\_page(), drupal\_deliver\_page(), and menu\_execute\_active\_handler(). It requires the Devel module, as it uses one of its functions.

This is the output given by `dsm()`.

You can override the theme function used for the breadcrumb, implementing hook\_theme\_registry\_alter().

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['breadcrumb'])) {
    $theme_registry['breadcrumb']['function'] = 'theme_mymodule_breadcrumb';
  }
}

```

`theme_mymodule_breadcrumb()` is the function that replaces theme\_breadcrumb(), and it gets the same parameters.

> `$variables`: An associative array containing:
>
> * breadcrumb: An array containing the breadcrumb links.

The theme function should be overridden if you want to alter its output. If you want to alter the value of the variables passed to `theme_breadcrumb()`, with Drupal 7 you can implement a preprocess function.

```
function mymodule_preprocess_breadcrumb(&$variables) {
  // Your code.
}

```

---
Tags: 7, theming, hooks, breadcrumbs
---


# Question
Title: How can I make Private Messages in Drupal 7 with user user pictures like in Facebook?
There are many people who want to see their Private Message module in Drupal to look like Facebook - i.e. with user pictures. Pictures make messages more "personal" and "closer" than e-mails. I made it work in D5 and D6 by putting functions into template.php, but for D7 I can't find any such snippet that would work for D7.

I've written more about this here http://drupal.org/node/1549540 There's already much of the snippet there, but the DB query returns an error.

Can someone please help write a lasting solution for drupal user in D7?

# Answer
that's a great idea, I would love to see that too. Wouldn't it be easier replacing the default page with a view? Then you can style it any way you want. The "checkboxes" and actions could be done with VBO.
> 3 votes

---
Tags: theming, users, privatemsg
---


# Question
Title: How do web search engines handle view pages?
When search engines are examining the content of a Drupal site how do they identify content assembled by a view? A single view can have unlimited pages associated with it. In fact the entire content of a site can be provided that way.

Any resources on how these engines do their job in general (and for Drupal specifically) would be appreciated.

# Answer
> 1 votes
In the SEO world, this is known as Duplicate Content, and it's something you want to avoid as much as possible. \[1\]

This is dangerous territory for duplicate pages which can get you sandboxed by the search engines! \[2\]

in drupal you can reach same page with lots of links: `node/123`, `node/123/`, `content/some title` and ...

one solution is Global Redirect module

---
Tags: views
---


title: modifying data in a node

text:
# Question
Title: modifying data in a node
I have created a node with a cck select box which comes with a few possible values. How would I code a module to change the value from one value to another? For example, the default value of field\_model is Oldsmobile, and I want to write code which will change it to Toyota?

# Answer
> 0 votes
This depends ... D6 or D7 ... is the field a reference to something else (term, node, entity)?

Generally you have to write something that looks up the value of the item in the list, for example for a node reference:

```
  $modelcode='Toyota';

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->fieldCondition('field_models_code', 'value', $modelcode, '=');
  $result = $query->execute();
  $model_nid=array_shift(array_keys($result['node']));

  unset($result);
  unset($query);

```

Then you would take the $model\_nid and update your field in the form state:

```
$form_state['values']['field_model'][LANGUAGE_NONE][0]['value'] = $model_nid;

```

This example assumes D7 and a field set to node reference.

---
Tags: entities
---


title: Convert query to D7 for db_query_range

text:
# Question
Title: Convert query to D7 for db_query_range
How do I convert the query below properly to 7x?

```
$query = db_query('SELECT latitude, longitude FROM {zipcodes} WHERE city = UPPER("%s") LIMIT 1', $search_term);

```

```
$query = db_query('SELECT latitude, longitude FROM {zipcodes} WHERE zip = "%s" LIMIT 1', $search_term);

```

The Coder module advised that I change it to db\_query\_range so I tried the code below.

```
$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, array(':city' => $search_term);

```

```
$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.zip = :zip', 0, 1, array(':zip' => $search_term);

```

# Answer
> 4 votes
As far as I can tell your code is fine except for a small syntax error; you're missing a closing parenthesis on the end of the statement. It should be:

```
$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, array(':city' =>$search_term));

```

It's often handy to split the arguments out into a separate array so this sort of thing is easily avoidable:

```
$args = array(':city' => $search_term);
$query = db_query_range('SELECT z.latitude, z.longitude FROM {zipcodes} z WHERE z.city = UPPER(:city)', 0, 1, $args);

```

---
Tags: 7, database
---


# Question
Title: How repeating field values in "EntityReference select list widget" as I would with "autocomplete widget"
my question is how to display "select list widget" like "autocomplete widget" when
I create or edit an entity, I mean with "add another field". I need this
because I need repeating field values in "EntityReference select list
widget" as I would with "autocomplete widget" or as shown in the module "Double Field". thanks and sorry for my english

# Answer
> 1 votes
I found everything I was looking for in the Multiple Selects module. Here is a quote about it (from the module's project page):

> ... provides a widget called Multiple Selects list for the the following fields types:
>
> * entity\_reference
> * node\_reference
> * user\_reference
> * taxonomy\_term\_reference
> * list\_integer
> * list\_float
> * list\_text
> * list\_boolean
> * commerce\_product\_reference
>
> Rather than having a multi-select field, this modules allows you to have multiple select fields with the traditional FieldAPI 'Add another item' button.

---
Tags: entities
---


# Question
Title: How to add jQuery to the user profile page only?
Me and Javascript/jQuery don't get along well ...

What I want to do is show the first 200 or so characters of a user's "about me" text and then expand it when you click the "more" link.

I added to my template.php

```
function bartik_preprocess_user_profile(&$variables){
  drupal_add_js('themes/bartik/js/moreless.js');

}

```

The moreless.js code is:

```
jQuery(document).ready( function ($) {
    $(".moreLess").hide();

    $(".moreLessSwitch").toggle(function() {
        $(this).html("<a href=#>Less</a>");
        $(this).prevAll(".moreLess").slideDown();
    }, function() {
        $(this).html("<a href=#>More...</a>");
        $(this).prevAll(".moreLess").slideUp();
    });
}(jQuery));

```

in user-profile.tpl.php I have:

```
stuff to always show
<div class="moreLess">stuff to hide...</div><br>
<div class="moreLessSwitch">[+] more</div>

```

This is the working jfiddle sample.

When I load a user profile nothing happens, I had all caches flushed. No js errors. When i copy the jquery code into the console it works. This has to be something dumb simple ;-)

Also, is this really the correct way to add conditional js to some pages?

# Answer
The code you should use is the following one:

```
(function ($) {
  $(function ($) {
    $(".moreLess").hide();

    $(".moreLessSwitch").toggle(function() {
        $(this).html("<a href=#>Less</a>");
        $(this).prevAll(".moreLess").slideDown();
    }, function() {
        $(this).html("<a href=#>More...</a>");
        $(this).prevAll(".moreLess").slideUp();
    }
  );
})(jQuery);

```

In Drupal 7, JavaScript using jQuery should be wrapped between `(function ($) {` and `})(jQuery);`. You should also use Drupal behaviors, similarly to what done in the batch.js file used from Drupal.

```
(function ($) {

/**
 * Attaches the batch behavior to progress bars.
 */
Drupal.behaviors.batch = {
  attach: function (context, settings) {
    $('#progress', context).once('batch', function () {
      var holder = $(this);

      // Success: redirect to the summary.
      var updateCallback = function (progress, status, pb) {
        if (progress == 100) {
          pb.stopMonitoring();
          window.location = settings.batch.uri + '&op=finished';
        }
      };

      var errorCallback = function (pb) {
        holder.prepend($('<p class="error"></p>').html(settings.batch.errorMessage));
        $('#wait').hide();
      };

      var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback);
      progress.setProgress(-1, settings.batch.initMessage);
      holder.append(progress.element);
      progress.startMonitoring(settings.batch.uri + '&op=do', 10);
    });
  }
};

})(jQuery);

```

The code in the JSFiddle works fine for me. It just be only a problem of wrapping the code correctly.
> 3 votes

# Answer
I came across an article "Painless collapsible Divs in Drupal". The irony for me is that I went through a lot of pain to get this simple feature working.

Ctools has a built in feature to do it with 1 line of code, ouch!

```
print theme('ctools_collapsible', array('handle' => 'Click me and you will see collapsed content', 'content' => $collapsed_content, 'collapsed' => TRUE));

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Is it possible to rate a page generated with Views using the fivestar module?
Fivestar works well with nodes, but is it possible to rate a page generated by Views? I can add the widget in a template, but how do I save the results? In the project description page of fivestar, it states that in Drupal 7 you can use it on any entity, but I don't think a Views page is an entity, is it? I found an old issue on the issue queue about this, but it was never updated once the new API was written.

# Answer
I normally use a "hidden" node to accomplish this. Typically, I will make a content type called something like "internal use". Then, I will make a panel page that contains an "inernal use node and my view. The node-ish actions then get associate with this node.
> 3 votes

---
Tags: views, rating
---


title: Drush enable/disable Devel modules

text:
# Question
Title: Drush enable/disable Devel modules
I love admin-menu's Enable Developer Modules menu item. How can I toggle this from the command line?

Admin menu already has a configuration of "developer" modules set up in settings.php. I can access this array with `drush vget admin_menu_devel_modules` (well sort of, that returns two entries). Now I want to 'pipe' those items to `drush enable`. I know that's not literally possible but this is my thought process.

How can I script this command?

# Answer
> 4 votes
I prefer to have a custom module that has dependencies for all the developer modules I need. I also set up this module to have some strongarmed variables (such as turning off preprocessing of css/js and any page caching), and enables a few developer blocks using Context (such as execute php and context inspector). This allows you to simply drush en/dis the one module to turn on/off all of your developer utilities.

Here's my Lullabot devel module that you can look at for an example.

# Answer
> 1 votes
The cleanest option might be to write your own Drush command from scratch. They don't have to be terribly complicated -- the 'sandwich' command is installed with Drush and serves as a nice template.

# Answer
> 1 votes
Another possibility for those who use a building framework like ant or phing is to define a target in your build.xml file with all the task that you need to perform to set up your perfect dev environment. Another target can be defined to undo the first. That way you can toggle between the two modes at will.

A brief example of such targets are below

```
   <target name="en-dev">
      <exec  command="drush --yes en devel devel_themer coder"  />
      <exec  command="drush --yes perm-grant 'Authenticated User' 'access devel'" />
      <exec  command="drush --yes perm-grant 'Annonymous User' 'access devel'" />
    </target>

    <target name="dis-dev">
      <exec  command="drush --yes dis devel devel_themer coder"  />
      <exec  command="drush --yes perm-revoke 'Authenticated User' 'access devel'" />
      <exec  command="drush --yes perm-revoke 'Annonymous User' 'access devel'" />
    </target>

```

In this case I could run `phing en-dev` to set up my dev environment.

For the opposite function I just run `phing dis-dev`

# Answer
> 0 votes
```
drush pm-enable `drush php-eval "echo 'ctools'"`

```

This would try to enable ctools; change echo ctools to one that formats the modules with a spaces between them

# Answer
> 0 votes
Not tested with this situation but xargs can take the results of one command and pipe as arguments to the next

```
drush vget admin_menu_devel_modules | xargs drush en

```

you may need to do a bit of sed in the middle if the variable that vget returns is not to drush en's liking.

---
Tags: drush
---


# Question
Title: Drupal 7 - Advice needed to accomplish the idea of embedding a view in a view
Using Drupal 7 - I have a view that displays all project assignments per employee. This view works properly and is displayed as a block on Department nodes.

I have another view that displays a page,"Department Directory". Where the directory lists fields of such as Department Name, Address, Phone, Fax, Email.

The idea I am trying to accomplish is to have a list of fields of the department, and then have it list the employee assignments. Example:

View Page: Departments:

Finance Department

Address 123

555-555-5555

Email@mail.com

(This is where the views employee assignment block fields would be displayed)

PERSONNEL ASSIGNMENTS:

John Smith: Complete Budget

Alan Wayer: Generate Monthly Expense Reports

---

Upon doing some research, the Views field view module gave me the results I needed, however, I read that this module is resource heavy. Is there a more efficient way that this can be accomplished?

# Answer
> 2 votes
Where did you read that Views is resource heavy? While there is some overhead to running Views, it is generally not significant unless you are getting enormous amounts of traffic. Your system sounds like it will be used internally, so I highly doubt that you will run into performance issues.

Views is a visual SQL query builder. It is also the most popular module for Drupal and one of the best supported modules. The alternative to Views is to write the SQL queries yourself, but unless you're a SQL expert this is error-prone and time consuming. You can always do everything in Views first and then re-write some of the queries manually if you run into performance problems.

# Answer
> 1 votes
I agree with @Patrick Kenny. Views is not very resource heavy. And the queries coming through views are much more optimized than generally a normal programmer would write.

Plus there are caching options for views. You can set the caching time for views which will mean that the results will be cached. So now do you understand how powerful it is? Check the caching options under advanced section on the right side of the views setting page.

Now two embed views inside a view, there are quite a few options.

**First** and very simple is to embed the view writing a code on the header or footer. Although I agree that it is not the best way to do things. But then, sometimes such things are done to quickly turn things around. :)

**Second** is, if both the views are blocks you can write one block and using php code embed the two view blocks inside that block. And then you can place that block where every you want to.

And the **last** but a very good way is to use panels. But yes, its a big module and if you just to embed a view inside a view, this can be an overkill and this might be a bit resource heavy then.

Hope these methods help.

---
Tags: 7, views
---


title: Views Menu Tabs and Ajax?

text:
# Question
Title: Views Menu Tabs and Ajax?
Is it possible to use menu tabs/default menu tabs available in Views, along with ajax, so that hitting a tab does not load a new page?

# Answer
If you want to user tabs and have blocks inside them coming from then, then one very beautiful module which you can use is Drupal Quick tabs: http://drupal.org/project/quicktabs

This module works amazingly. It also takes arguments and allow you to do a lot of advanced modifications like Ajax call to the tabs or directly load them etc. You can check the Techtree website for an example of quick tabs that we have used in the side bar.
> 1 votes

---
Tags: views, ajax, routes
---


# Question
Title: How can we associate an image & textfield with a specific Domain in Drupal 7?
I am using two subdomains in my drupal project. I would like to associate image and textfields with specefic domain only.

# Answer
Domain Fields module works for me as it restricts fields to specific content type on specific domains.
> 1 votes

---
Tags: domain-access
---


# Question
Title: How to show children terms of parent terms in taxonomy?
Ok this thing is driving me completely haywire! I think this question has been asked before in some ways but I seem to be too dumb to tweak those to my requirement.

I've created a taxonomy vocabulary named "Brands" of products like so

Level 1: Brand names like Logitech, Gigabyte etc.

Level 2: Product categories like mice, keyboards, headphones etc inside each brand.

Level 3: The actual products inside each categories.

These levels can go deeper if necessary. Like in mice there can be wireless and standard ones. I hope I'm being clear. I've also created a menu from this taxonomy by using "Taxonomy Menu" and "Superfish" modules.

Now what I want is that when I click a menu entry (could be of any level) the page loaded should list it's children inside it. Like clicking Gigabyte should list only the names of categories of products inside the page not the actual products. I've gone through many insane combinations of options in views but to no use. So far I've only managed to show product teasers on every level but that's not what I want.

I want to do things the way it's done on the following site: http://www.shophive.com/

I'm using Drupal 7 by the way.

Please please please help me with this as I'm on a deadline! :(

# Answer
Here's one way to do this.

Use Panels to override `term_view`.

Edit the overridden `term_view` panel. Add a new variant with the default settings. In the `Content` section, add content. You want a `List of related terms`, which can be found under `Taxonomy term`. You can set this to be the `Child terms` of the `Term being viewed`.
> 3 votes

# Answer
I don't really know how you are configured, but I would try using taxonomy menu for the configuration walk-through, this is a good help page.

Hope this helps, cheers!
> 0 votes

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


title: Not able to remember the user id

text:
# Question
Title: Not able to remember the user id
I am new to Drupal. I have created a menu on user page to edit the account settings as `user/uid/edit`.

I just want to know how to replace `uid` with the user id of current user.

# Answer
> 2 votes
I have faced a similar problem in the recent past and found two solutions for the same.

## Short solution

Install Me alias module, and then replace your *uid* with *me*, and the module will replace *me* with the *uid* of respective user.

## Long solution

Install Menu token module and use token to replace the path of the menu. Go to edit menu and in the path, do the following

---
Tags: routes, users
---


# Question
Title: How to get all records of a view with paging?
I have a view with 20 records, displaying 10 records on each page. I have a field check-box with custom handler to check and uncheck each record. I am using the `$this->view->results` to loop through all the records of view to check or uncheck on different events. This logic is working fine.
Now, I have added a new button to select all the records of view i.e. 20 records of both pages. Is there a way I get all the records of view with paging. In my case I want to get/select all the 20 records which are displayed on two pages. If I print `$this->view->results`, it has only 10 records which are displayed on page 1. Is there any view array element which have all 20 records?

# Answer
If you don't mind installing another module, try Views Bulk Operations. Views Bulk Operations (often abbreviated VBO) allows you to add "select all on page/select all everywhere" checkboxes and also offers additional functions such as using batch API to process operations when there are too many to do at once (if you had 20,000 records instead of 20).

Node One has a tutorial on VBO.
> 2 votes

---
Tags: paging, views
---


# Question
Title: User Profile Image not showing correctly
I want to show the profile and few content fields for a user profile. For this, I have used views module. Now the problem is that when I select imagecache preset to profile image(which I have defined as 150x200), the output is pathetic. It shows the profile images of around 63x63 size. I thought that the imagecache module might not be working. So I uninstalled and reinstalled the image and imagecache modules, but all in vain. Then I thought of checking into the imagecache folder whether the images are being resized, and to my amazement , the images inside sites/default/files/imagecache/profile\_image/pictures/ folder were all of the dimension defined by me for profile image i.e 150x200 . So the problem seems to be only while these images are shown on the frontend.

Any idea about this?

# Answer
> 1 votes
Go to this link your\_url/admin/config/people/accounts

here you will see field "Picture upload dimensions" do not write any dimension in this field , save it and then add profile picture for user

this works in Drupal 7

---
Tags: media
---


# Question
Title: Expand children menu items with parent link, without javascript
I've build a main-menu, and a sub-menu with Menu block. The sub-menu shows up if I'm on the article with the represented link. It works like it should.

**Question**: How can can I expand all childrens of a parent menu-link without Javascript?

A short wireframe for the overview.

# Answer
If I understand you correctly then setting the parent link to "Show as expanded" should get you the desired result. You can see the option when you go to Structure -\> Menus -\> list links (of the correct menu) -\> edit (the parent menu item which should have it's child links always displayed).
> 1 votes

---
Tags: 7, routes
---


# Question
Title: How to display additional fields in user profile?
I have added three fields to user profile (field\_firstname, field\_lastname, field\_user\_gender) and I want to display them on user profile page. Default `render($user_profile)` displays values of those fields continuously, for instance: *JohnMalkovichMale*

How I can do this right? And how I can get names of fields?

# Answer
This is just a CSS issue. Use developer tools/firebug to determine the class/id of the element wrapping each field, and add a CSS rule such as the following to your theme:

```
.field-wrapper-1, .field-wrapper-2 { display: block; }

```
> 3 votes

---
Tags: theming, users
---


title: Some trouble autopath

text:
# Question
Title: Some trouble autopath
I have some trouble with user path aliases. I want that every user has a small page under `/member/username`. To enforce that I build in the settings (`/admin/config/search/path/patterns`) under `user path` the plattern: `member/[user:name]`.

This seems to work fine but if I look at the contact link I get the link `/user/1/contact` I expect the link `http://example.com/member/username/contact`.

I have the same problem for some other links like editing any node. E.g. I have a link in my menu called *Updates* which is aviable under `/updates` but when I try to edit this one I see the url `/node/123/edit`.

I know that there is a module called `Extended Path Aliases` but this one breaks one of my own modules.

The problem there is that I use taxonomy to build paths for topics e.g. photography and sports. Normal posted news are then aviable under `/photography/a-great-day` or `/sports/scores` that will work with `Extended Path Aliases`, but it compleatly breaks my module with this pathes `sports/event/%date` (notation from menu\_hook). That one seems to be routed to `/sports`.

# Answer
> 0 votes
I got the solution via IRC. Simply install and activate Sub-pathauto.

---
Tags: 7, path-aliases, uri
---


# Question
Title: Moved site to new server and I can't log in
I'm migrating a client's site to a different server because we're changing web hosts. The domain name still points to the old site for now and I either use an ip address or a temporary url to preview the new site. However, since I moved it, I can no longer log in, I get an "access denied" error message. Is this a known issue? How can I resolve it?

EDIT: I oddly don't have this problem when I download the site to my hard drive and run it locally.

# Answer
> 3 votes
This happened to me so many times back in the days of Drupal 6.

99% of the time it was caused by the anonymous user record having been removed from the `users` table in the database.

Try adding a user to that table with a uid of `0` (and all other fields empty); if the above is what's causing the problem, that should fix it.

---
Tags: 6, migrations
---


# Question
Title: HTML special characters changed to foreign characters
We have a Drupal 6 website and are using tinymce for the editor. Many of our pages included the pound (£) sign as well as other special characters. All of these have now been changed into foreign symbols. The pound sign now appears as Â£ and other strange symbols such as â€“.

I've checked the source code and the original characters have been changed into the strange new characters. It seems like the only way to fix it is to manually edit all the pages. I checked the character encoding tag and this is set to utf-8.

Can anyone help with why this might have happened in one go? The only thing I can attribute it to is possibly running update.php. Also, is there an easier way to convert then all back again?

Many thanks,

Ben

# Answer
> 1 votes
It should work in a proper Drupal environment

> Several people have asked how to specify the character encoding that Drupal uses. The short answer is: you can't.

How can I change Drupal's character encoding

> Drupal uses UTF-8 for encoding all its data. This is a Unicode encoding, so it can contain data in any language. You no longer need to worry about language specific encodings for your website (such as Big5, GB2312, Windows-1251 or 1256, ...). Also, when Drupal imports external XML data (such as RSS or XML-RPC), it is automatically converted into UTF-8 (iconv support for PHP will be required for most encodings).

From Stackers

---
Tags: 6, nodes
---


# Question
Title: (dis)advantages of staging dev->production using 'drush rsync' vs 'git'?
I set up a Drupal site under git control for development work.

It's parented in a master, bare GIT repo, and as changes are made in my various project-work git clones, and pushed back to the master, a post-update hook immediately pushes the changes to a single live Staging website (http://staging.loc.). Nothing special, works as expected.

I've also drush-aliased the site "@STAGING". On occassion, I want to promote my changes from the Staging site to a production server.

Two relatively straightforward methods come to mind:

(1) At a point in time when the Staging site appears stable, create the Production site as a git checkout from the master repo,

(2) use `drush rsync` \+ `drush sql-sync` from the staging site to the production site.

Both can be made to work. Other than the fact that (2) seems more Drupal-centric/aware by nature -- drush is, after all, a Drupal-specific set of tools -- what are the relative merits of the two approaches?

Is there any particular reason I should consider (1) over (2)?

In either case "Everything" is under at least one instance of revision control ...

# Answer
> 3 votes
I have used both techniques. Both can be used to guarantee that the same files that you test on @stage end up on @live. The advantage of rsync is that you do not end up with extra files (e.g. ".git" and associated) on your production server. I tend to rsync to a vps, and use git on a box I own (e.g. intranet sites).

# Answer
> 1 votes
The problem with using drush rsync is that if you have multiple people pushing changes to the server.

Your example only shows one person pushing changes.

If you have developer A pushing her changes and then developer B pushing his changes you want git to mop up the conflicts, or make developer B mop up the conflicts.

# Answer
> 1 votes
I actually use both. svn/git and rsync serve two different purposes. svn/git is for source control, `rsync` and `sql-sync` is for syncing staging and prod efficiently. `drush rsync @staging @prod` is very hard to beat in terms of simplicity, and is dreadfully easy to integrate in most any `continuous Integration` environnment should you want to dive even deeper in code quality craziness/methodologies.

# Answer
> 1 votes
Personally I use Git for version control, deployment and syncing various server codebases and then rsync to move/sync users files (ignored by adding certain paths to the .gitignore file).

---
Tags: drush, version-control, staging
---


# Question
Title: How to add an attribute to a node-taxonomy relationship?
I'll try to explain my problem through an example ...

I have to do a recipe site with Drupal. I have an *ingredient* taxonomy and for each recipe I have to assign taxonomy and a value.

Example: 4 Eggs, where 'Eggs' is a taxonomy term.

Is there some module that can help me with this?

# Answer
If I understand you right you might want to use the Relation module (Drupal 7 only):

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.
>
> Relations are entities and can therefore have fields. This makes Relation the most flexible and powerful relation model out there.

You could create a relationship entity with a 'Value' field (to store e.g. the number of eggs) and then use that entity as a relationship field to link your nodes and taxonomy terms.
> 0 votes

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


title: Where is the $content of a page build?

text:
# Question
Title: Where is the $content of a page build?
I would like to add something to my `$content` variable to add on my node template file, but where is this variable composed? I assume it's in the template.php file but what specific function composes the content of the `$content` variable?

# Answer
If you are referring to the `$content` variable that is available in node.tpl.php, its value is set in template\_preprocess\_node() from the following code:

```
  // Helpful $content variable for templates.
  $variables += array('content' => array());
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

```

`$variables['content']` is then passed to field\_attach\_preprocess().

```
  // Make the field variables available with the appropriate language.
  field_attach_preprocess('node', $node, $variables['content'], $variables);

```

To alter the content of the `$content` variable, you can implement hook\_preprocess\_node() (in a theme, or a module), or hook\_field\_attach\_preprocess\_alter().

Remember that what in a template file is `$content`, in other places is `$variables['content']`.
> 4 votes

# Answer
In template.php write this function

> function hook\_preprocess\_page(&$variables) { // $variables will contain that content variable }

of you can use

> function hook\_preprocess\_node(&$variables) { // $variables will contain that content variable }
> 0 votes

---
Tags: 7
---


# Question
Title: Views exposed filter redirects to wrong url
After submitting the filter settings, on a page (panel in ctools Page manager module) with view content pane, the filter path (in URL) instead of being applied to the current page (with view), it is added to the root domain (home page).

Please give a tip what might be wrong with settings?

# Answer
> 13 votes
View Settings - PANE SETTINGS (middle column) - Use Panel path:Yes

---
Tags: 7, views, panels
---


title: .htaccess www. redirect in Dev Desktop

text:
# Question
Title: .htaccess www. redirect in Dev Desktop
Possible stupid question but worth a punt...

My local OS X setup uses Acquia Dev Desktop. I recently changed a remote site's .htaccess file to redirect all no www. URLs to their www. equivalents (done my uncommenting the relevant 2 lines already in Drupal 7 core .htaccess). Pulling this change down to my local setup now means that my local dev version can no longer be navigated to.

Running cron and clearing all caches via Drush doesn't seem to help in any way.

Do I have to use a different .htaccess file for local and remote setups or am I missing something here?

# Answer
> 2 votes
Yes, when you made a change to the remote `.htaccess` file, you made a *system specific* change that doesn't always apply if you copy the file elsewhere.

An option is to keep `.htaccess` stock (ie, the same as the version that came with Drupal) and do your site-specific configuration in an Apache configuration file. This way, when you transfer files, update core, drush pm-update, etc, you don't have to worry about local changes to `.htaccess`.

On a high volume site, it can make sense to ditch the `.htaccess` and move everything to an Apache configuration file. When the directives are in a config file, they get parsed/saved when Apache starts. When you use `.htaccess`, it gets parsed each and every request and not saved. Apache will also traverse the directory tree looking for an `.htaccess`.

# Answer
> 2 votes
Yes, you need to use a separate `.htaccess` file for your local version of the site.

It often makes sense to sync just the `sites/all` and/or `sites/default` folders (minus `settings.php` of course) of a Drupal site, so you can avoid this sort of problem without even having to think about it; unless you're hacking at core of course, which isn't recommended anyway :)

---
Tags: redirection, .htaccess
---


# Question
Title: Clean and easy way to add meta tags to my D7 website
I'm looking for a easy way to add meta tags to my D7 website. Not that I'm afraid of code or anything like it, but the content managers (Marketing =\> biggest IT noobs you've ever seen) want to add meta-tags by using the Drupal UI.

I've checked the MetaTags Quick-module, but it seems like this module is only capable of adding path-meta tags. Are there any alternatives? Or what is the most clean way to add meta tags do my Drupal 7 website?

# Answer
For Drupal 7 the Meta tags module is the way to go:

> The Meta tags module allows you to automatically provide structured metadata about your website.

MetaTags Quick is also good, but Meta tags has more features.
> 3 votes

---
Tags: 7, meta-tags
---


title: How to use smarty in Drupal 7

text:
# Question
Title: How to use smarty in Drupal 7
I have some prior experience in PHP programming but I had used Smarty as my template engine, and found it easy to use. I read that Drupal is making use of PHPTemplate as template engine. So, I just wanted to know how to implement Smarty template engine in Drupal?

# Answer
While there is a Smarty module, it has no release for Drupal 7 and I doubt there will be one.

For Drupal 4 and 5, there were various efforts made to use different template engines. However, nearly all contributed themes for Drupal 6 and 7 are done in PHPTemplate and almost all documentation and available support are for PHPTemplate.

Even if you're already familiar with Smarty, if you're going to use Drupal seriously for more than one project I would highly recommend learning PHPTemplate. At this point, you would have to do work to integrate Smarty into Drupal 7 on your own, which would almost certainly be harder than just learning PHPTemplate. Going with Smarty will also limit your support options.
> 8 votes

---
Tags: 7, theming
---


# Question
Title: How to properly use two contextual filter for taxonomy
this is my case:

* I have a content type called "norm".
* Each norm has two fields with taxonomy terms: "issuing institution" and "norm type".
* Each taxonomy field has its own vocabulary.

I'm making a View that will:

* Filter all the "norms" that are issued by "institution A" or "institution B".
* Has two contextual filters. One for "insitution", second for "norm type".
* If the first parameter is not given, just show a summary with the instituions (in this case, just two institutions). \[This is working\]
* Then, if the second parameter is not given, just show a summary with the "norm type". I mean this will be a list of norm types that has been issued by institution %1 (first parameter).

But, the last is not working. It shows again the instituion.

How can I do this kind of thing?

# Answer
This happens because the views checks the first parameter and the first parameter overrides the second parameter. In your case, if you rearrange parameters so that parameter 2 comes before parameter 1, you will see this time views working with parameter 2 and not with parameter 1.

You can fix this behavior by creating two separate pages in views and each page will override the behavior of the other by selecting For:"This page(override)" option.

In the first page add the two contextual filters(parameter 1 and parameter 2). While adding the contextual filters you have to select For:"This page(override)".

In the second page of the views, add the two contextual parameters, this time add parameter 2 before parameter 1. In this case also, while adding the parameters you have to select For:"This page(override)".

Good luck!
> 1 votes

---
Tags: 7, views
---


title: how to render links as menu tabs

text:
# Question
Title: how to render links as menu tabs
I have created a block that generates some links. I want to display these links as menu tabs in my website. This is the php code I have written inside block.

```
<?php
  $current_url = current_path();
  $param = explode("/", $current_url);
  $nid = $param[1];

  $type = db_select("node", "n")
            ->fields("n", array("type"))
            ->condition("nid", $nid, "=")
            ->execute()
            ->fetchAssoc();

  switch($type['type']) {
    case "description":
      $current_desc_link = $current_url;
      $current_demo_link = db_select("field_data_field_desc_demolink", "fddd")
                          ->fields("fddd", array("field_desc_demolink_url"))
                          ->condition("entity_id", $nid, "=")
                          ->execute()
                          ->fetchAssoc();

      $howto_entityid = db_select("field_data_field_howto_demolink", "fdhd")
                          ->fields("fdhd", array("entity_id"))
                          ->condition("field_howto_demolink_url", $current_demo_link['field_desc_demolink_url'], "=")
                          ->execute()
                          ->fetchAssoc();

      $current_howto_link = "node/" . $howto_entityid;

      break;

    case "how_to":
      $current_howto_link = $current_url;
      $current_demo_link = db_select("field_data_field_howto_demolink", "fdhd")
                          ->fields("fdhd", array("field_howto_demolink_url"))
                          ->condition("entity_id", $nid, "=")
                          ->execute()
                          ->fetchAssoc();

      $desc_entityid = db_select("field_data_field_desc_demolink", "fddd")
                          ->fields("fddd", array("entity_id"))
                          ->condition("field_desc_demolink_url", $current_demo_link['field_howto_demolink_url'], "=")
                          ->execute()
                          ->fetchAssoc();

      $current_desc_link = "node/" . $desc_entityid;

      break;

    default:
      $desc_entityid = db_select("field_data_field_desc_demolink", "fddd")
                          ->fields("fddd", array("entity_id"))
                          ->condition("field_desc_demolink_url", $current_url, "=")
                          ->execute()
                          ->fetchAssoc();

      $howto_entityid = db_select("field_data_field_howto_demolink", "fdhd")
                          ->fields("fdhd", array("entity_id"))
                          ->condition("field_howto_demolink_url", $current_url, "=")
                          ->execute()
                          ->fetchAssoc();

      $current_demo_link = current_url;
      $current_desc_link = "node/" . $desc_entityid;
      $current_howto_link = "node/" . $howto_entityid;

      break;
}
?>

```

I want to render `$current_demo_link`, `$current_desc_link`, `$current_howto_link` as menu tabs in drupal webiste. I have tried `menu_tree_output` but I have to create menu links in Db. Is there any other way to render the links as menu without converting this as menu links.

# Answer
Maybe try something like this?

```
$output = '<ul class="tabs primary">';
$output .= '<li><a href="' . url($current_demo_link) . '">demo link title</a>';
$output .= '<li><a href="' . url($current_desc_link) . '">desc link title</a>'
$output .= '<li><a href="' . url($current_howto_link) . '">hot to link title</a>'
$output .= '</ul>';

```
> 1 votes

---
Tags: 7, routes
---


title: Migrating with the migrate module

text:
# Question
Title: Migrating with the migrate module
I am using Drupal 7 and the latest Migrate module. I am trying to create a class to migrate products from an OpenCart DB into my new D7 site. I figured out all the SQL I need and got most of that programmed in. But I am having a little trouble understanding how I am going to do the categories.

My migration target is Ubercart.

What I am trying to understand sits in the migrate\_example module which is a submodule of Migrate. Specifically I am looking at the wine.inc file at the WineWineMigration class. I am trying to understand the term migration.

I have two lists that will become taxonomy terms in the Ubercart products. First is the categories. I have setup the categories manually, so when I bring the list of those over (using the GROUP\_CONCAT SQL func) I will have a bunch of IDs that I will map using an array that will hold all the ID conversions. That is fine, but when I look at their BestWith info that they are migrating it shows that it is using the WineBestWith class above to import the term.

I am confused by this because it looks like some kind of secondary migration of terms. Is that what is happening? Further, is this where I would put my mapping array, in this term migration class?

The next thing I need to do is deal with tags. In OpenCart we have a bunch of free form tags. And when I manually create a product in Ubercart I have an autocomplete field for tags. In that field I can just put in a comma separated list of terms and it creates multiple terms. Can I do the same thing in the Migrate module? Can I just map the field to the list of comma separated terms? Will that add the tags in there for each product?

# Answer
I'm working on the same problem right now so I understand your confusion. You have a lot of questions, but I think they can be summed up into a singular question:

> How does the Migrate module handle migrating a normalized database into a Drupal installation?

It's definitely not straightforward, but here's my understanding of how it works. We'll start from the top (WineWineMigration) going down and ask questions as we go.

We start off by looking at the code at the top of the `WineWineMigration` class.

```
...
$this->dependencies = array('WineVariety', 'WineRegion',
  'WineBestWith', 'WineUser', 'WineProducer');
...

```

This tells the Migrate module that in order to migrate your Wine content, the dependent migrations - WineVariety, WineRegion, WineBestWith, WineUser, WineProduce - must be completed first.

So what we've learned here is that **migrations can be dependent on other migrations**.

Next we have the mapping between the table that currently holds the base wine info and the Drupal node:

```
$this->map = new MigrateSQLMap($this->machineName,
  array(
    'wineid' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'description' => 'Wine ID',
      'alias' => 'w',
    )
  ),
  MigrateDestinationNode::getKeySchema()
);

```

This is pretty straightforward so if you need clarification I will provide it.

I'm going to skip over some interim stuff that isn't really pertinent to hooking up the various categories and wine objects.

Now we get to the field mappings. Observe:

```
// Mapped fields
$this->addFieldMapping('title', 'name')
     ->description(t('Mapping wine name in source to node title'));
$this->addFieldMapping('uid', 'accountid')
     ->sourceMigration('WineUser')
     ->defaultValue(1);
// TIP: By default, term relationship are assumed to be passed by name.
// In this case, the source values are IDs, so we specify the relevant
// migration (so the tid can be looked up in the map), and tell the term
// field handler that it is receiving tids instead of names
$this->addFieldMapping('migrate_example_wine_varieties', 'variety')
     ->sourceMigration('WineVariety')
     ->arguments(array('source_type' => 'tid'));
$this->addFieldMapping('migrate_example_wine_regions', 'region')
     ->sourceMigration('WineRegion')
     ->arguments(array('source_type' => 'tid'));
$this->addFieldMapping('migrate_example_wine_best_with', 'best_with')
     ->separator(',')
     ->sourceMigration('WineBestWith')
     ->arguments(array('source_type' => 'tid'));
$this->addFieldMapping('field_migrate_example_wine_ratin', 'rating');
$this->addFieldMapping('field_migrate_example_top_vintag', 'best_vintages');

```

See where it says:

```
->sourceMigration(...)

```

This indicates to the migration that in order to map this field, another migration must be satisfied first. I believe this is the "secondary migration" that you spoke of. Let's use the `region` field mapping as the example here. Breaking it down...

```
$this->addFieldMapping('migrate_example_wine_regions', 'region')
     ->sourceMigration('WineRegion')
     ->arguments(array('source_type' => 'tid'));

```

This says that the category region in the source database is mapped to a region vocabulary term. As the TIP comment states in the field mappings code chunk, it assumes that mappings are made based on field\_names, but since we are dependent on a secondary migration as you put it, we need to specify the migration it is dependent on and instruct it to use tids instead of field names.

So pretty much for every normalized table you have in your source database, you're going to be specifying a migration for each, and then in the relevant field mappings that involve those tables, you'll be specifying dependent migrations in your field mapping calls, as well as the dependent migrations declaration at the beginning of each migration.

I hope this helps. I don't fully understand this myself so I used this question as an opportunity to enhance my understanding of how Migrate relates databases. As I learn a bit more I'll update my answer accordingly.
> 14 votes

---
Tags: taxonomy-terms, migrations
---


# Question
Title: 7 - Views 3 - Displaying taxonomy description in a block
I am trying to create a view displaying a description of the current taxonomy term. This view will be a block in the taxonomy/term/% page, so the idea is that it uses the argument passed to pick the description in the database.

My view works fine in the Views' preview but does not display any result on the pages which probably means that the argument is not passed to the block. Can someone help me fix my view?

**EDIT**

Contextual filter

The URL is /taxonomy/term/% and I am using pathauto aliases.

# Answer
> 0 votes
> The URL is /taxonomy/term/% and I am using pathauto aliases.

If you're using aliases I assume that your URL is something like some/path/your-term-name.

In that case I had exactly the same issue a while ago. You should try setting Filter Value Type to "Term name converted to term ID and check "Transform dashes in URL to spaces in term name filter values".

Also make sure that proper value is provided to the filter.

In the WHEN THE FILTER VALUE IS NOT AVAILABLE section select Provide default value and then select Raw value from URL and specify url component to provide as a default value. Unfortunatel "Term ID from URL" option doesn't work as you might expect in case of aliases so you need either provide default value from URL using Raw value option or even using PHP Code option. If you choose this option, you might find the following piece of code useful:

```
$get = explode('/', $_GET['q']);
return $get[2]; //the "2" constant assumes that your term name is a third path component

```

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


# Question
Title: Is it okay to ignore the error notices I get on a Drupal site?
My Drupal 7 site has many error notices like

> Notice: unserialize() \[function.unserialize\]: Error at offset 225 of 305 bytes in variable\_initialize() (line 943 of /site/includes/bootstrap.inc).

or

> Call-time pass-by-reference has been deprecated in drupal\_load() in bootstrap.inc

The site still works inspite of the errors. Is it okay to ignore these error notices?

# Answer
Between the two errors, the first is more worrying.

As variable\_set() passes the variables value it receives to `serialize()`, if `unserialize()` is not able to understand the saved data, it means the database content is probably corrupted. variable\_initialize() calls `unserialize()` using the following code.

```
  // Proceed with variable rebuild.
  $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  cache_set('variables', $variables, 'cache_bootstrap');
  lock_release($name);

```

The second error says the code is using a feature that is deprecated, which means that in future PHP versions the code could not work anymore, but in the actual PHP version is still working.
> 3 votes

# Answer
I'd say it's okay to ignore *certain* error notices. I usually google them up, first - with full text, then stripping the lines number. If I get a bunch of results pointing to other users' claims, I can then get the idea of what is going on, and sometimes - get a confirmation there's nothing I can do about that.

I used to have many bootstrap.inc errors before I learned to always do module updates one by one, rather than en masse, and always follow each by visiting /update.php to let the hooks pick up necessary database updates.
> 2 votes

---
Tags: 7
---


title: Custom field storage, Per field

text:
# Question
Title: Custom field storage, Per field
How can I alter a field's storage property? What's the correct hook to use to alter `$field['storage'] = 'my_custom_storage';`?

I am currently using the global db variable `field_storage_default` but I find that to be gross. I don't want to do it for all fields.

# Answer
I thought this can be done using hook\_field\_create\_field, but it's not possible. Using that hook and then calling field\_update\_field will not work because the update does not allow this:

```
  if ($field['storage']['type'] != $prior_field['storage']['type']) {
    throw new FieldException("Cannot change an existing field's storage type.");
  }

```

Drupal doesn't want you to screw up existing data. So being careful and knowing what you are doing, the existing fields could be modified in the `field_config` table in the database. Reimplementing field\_update\_field you could do:

```
/**
* Implements hook_field_create_field().
*/
function mymodule_field_create_field($field) {
  if ($field['type'] == 'fieldtypetostore') {
    $field['storage'] = array(
        'type' => 'mymodule_custom_storage',
        'settings' => array(),
        'module' => 'mymodule',
        'active' => 1,
    );

    // Build record to update.
    $record = array(
      'id' => $field['id'],
      'storage_type' => $field['storage']['type'],
      'storage_module' => $field['storage']['module'],
      'storage_active' => $field['storage']['active'],
    );

    // Update the field storage.
    $primary_key = array('id');
    drupal_write_record('field_config', $record, $primary_key);
  }
}

/**
* Implements hook_field_update_field().
*/
function mymodule_field_update_field($field) {
  mymodule_field_create_field($field);
}

```

The best way to do this is to create the fields in your module that you need to use and at that time, set the storage for the field. It's cleaner than changing existing fields.
> 3 votes

# Answer
I am using this `hook_field_storage_info_alter()` to alter the storage field settings.

If yours executes last of all the modules, then you can change any storage field settings here.
> 0 votes

---
Tags: entities
---


title: Confirm module uninstall

text:
# Question
Title: Confirm module uninstall
I have written a module that creates a node type and I want to put in a warning on uninstall that lets the user know that the nodes created under that node type will be deleted if they continue to uninstall the module.

Now someone suggested that I use the confirm\_form function. But I don't see how this would work or even apply in this case since it has to integrate with the hook\_uninstall function for the module.

Any thoughts on this? Thanks!

EDIT: This module is written in Drupal 6 with a Drupal 7 version coming once this one has been approved by the Drupal community (my first community posted module, so I am not yet sure how to create the separate version branches yet).

# Answer
> 1 votes
In Drupal 6 you can alter the system modules uninstall form.

```
function MYMODULE_form_system_modules_uninstall_alter(&$form, &$form_state) {
  if (isset($form['modules']['MYMODULE'])) {
    //alter form how you would like
  }
}

```

The only change for Drupal 7 is there is an additional function argument

```
6       hook_form_FORM_ID_alter(&$form, &$form_state)
7 – 8   hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

```

NOTE: This form gets call on the /admin/module/uninstall & /admin/module/uninstall/confirm. If you just want it on one then add an additional case to the if statment, checking the path.

# Answer
> 1 votes
A module that is uninstalled through the user interface is first disabled, and then uninstalled. As consequence of this, the code that shows the user a warning before the module is uninstalled cannot be contained in the module that implements the content type. It should be contained in a module that is required from the module implementing the content type; in this way, the module that would warn the user about the content type being deleted could not be uninstalled before the module implementing the content type. (I will report after why I think that implementing this code is not worth the time spent.)

Supposing that base\_module.module is the module showing the warning, and content\_type.module is the module implementing the content type, you could write the following code. (The code is for Drupal 7, but similar code could be easily written for Drupal 6.)

```
function base_module_menu_alter(&$items) {
  if (isset($items['admin/modules/uninstall'])) {
    $items['admin/modules/uninstall']['page arguments'] = array('base_module_uninstall');
  }
}

function base_module_uninstall($form, $form_state = NULL) {
  if (!empty($form_state['storage'])) {
    if (isset($form_state['storage']['uninstall']['content_type'])) {
      // Show a warning message on the top of the page.
    }
  }

  return system_modules_uninstall($form, $form_state);
}

```

The code is simple, but it works just in a case: when base\_module.module is still enabled when content\_type.module is uninstalled; differently, the code adding the warning would not be shown. The problem is that the users could first disable the two modules, one at time, and then proceed with uninstalling them; if this happens, the warning would not be shown.

Considering this, and the fact other modules (including core modules) don't implement such code, I think that implementing it is not worth the time spent.
If such a feature is required, it should be implemented in Drupal. As the Node module is required in the default profile (otherwise, it would not be possible to create content types, and nodes), the warning would always be shown.

---
Tags: nodes
---


title: Different 'template path' per view?

text:
# Question
Title: Different 'template path' per view?
I want to get:

```
/mytheme-directory
  /front-slides
    /views-view--front-slides--block.tpl.php
    /views-view-unformatted--front-slides--block.tpl.php
    /views-view-fields--front-slides--block.tpl.php
  /front-4-cats
    /views-view--front-4-cats--block.tpl.php
    /views-view-unformatted--front-4-cats--block.tpl.php
    /views-view-fields--front-4-cats--block.tpl.php

```

instead:

```
/mytheme-directory
  /views-view--front-slides--block.tpl.php
  /views-view-unformatted--front-slides--block.tpl.php
  /views-view-fields--front-slides--block.tpl.php
  /views-view--front-4-cats--block.tpl.php
  /views-view-unformatted--front-4-cats--block.tpl.php
  /views-view-fields--front-4-cats--block.tpl.php

```

Can I use different 'template path' or do something else? easy way please :)

# Answer
> 1 votes
Yes, there are instructions for doing this on Drupal.org.

Also, here's a general article on organizing your theme files in Drupal.

---
Tags: 7, views, theming
---


title: Create submittable review form

text:
# Question
Title: Create submittable review form
I want to be able to allow users to rate businesses on various factors such as staff helpfulness and quality of clothing. I've been told that the best way to create the content type for the review form would be through the use of integer fields. I have now set up that content type, but am not really sure how to allow users to view/submit the review.

When I create content with the type "review," all that is displayed to the user is a comment section. They cannot see any of the selectable fields created in the content type, let alone submit them, because no values were defined by myself when the content was created. How would I go about making a displayed version of the form, with the menus exposed (in a similar fashion to exposed filters in Views, I suppose).

After the displayed form is created, I need a way to allow it to be submitted. Obviously, the review form would be useless if the information can't be submitted into the database to be later displayed in the reviewed business's page.

EDIT: A suggestion below suggests using webform, but as far as a I can tell, there is not a way to display the results of the form within another node. So, although webform presents a way to submit reviews and for me to see the results, there is no way to display them without manually inputting the average ratings into the nodes that the reviews are related to.

# Answer
> 1 votes
Normally, the way you implement this is you create a `Content type` Review, but you don't actually create the node (an instance of the content type, "1 review") yourself as an administrator. Instead, you give the users permissions to create nodes of that content type.

In this case, then, there isn't one review per restaurant. Each user creates a review for each restaurant that they would like to review, and then you can use the Views module to display all the different reviews. This will give you a model like the product reviews on Amazon.com, where each product often has a number of reviews from different users.

# Answer
> 1 votes
I recommend checking out the Webform module. It seems like the best way to handle this type of functionality.

---
Tags: forms
---


# Question
Title: How to enable module when there is a WSOD (blank page)?
Use case: I enabled a module, without enabling the required module. I saved the configuration on the modules page and it showed me the following screen -

I clicked "Continue" and then I get the WSOD (blank page).

I added error reporting php code in my index.php in root directory. It showed a fatal error - Fatal error: Call to undefined function variable\_realm\_switch() in /mysite/sites/all/modules/i18n/i18n\_variable/i18n\_variable.module on line 54

I cannot go back to the admin pages to enable the required module, because of WSOD. Is there a way to enable the module from the code? I cannot delete the modules involved in this error, because I will end up losing the data associated with the modules.

# Answer
> 7 votes
Using phpMyAdmin or any other database management software (or via command line mysql if you are comfortable with that), find the name of the module you wish to enable or disable in the `system` table. Set the `status` for that module to `0` for disabled or `1` for enabled.

mysql command:

```
UPDATE  `database_name`.`system` SET  `status` =  '1' WHERE  `system`.`name` =  'module_name';

```

phpMyAdmin screenshot:

I also recommend installing Drush on your server. This will allow you to execute commands like enabling/disabling modules, clearing caches, etc. from the command line, which is very handy in situations where you cannot access the Drupal admin because of a WSOD.

---
Tags: 7, updating, wsod
---


# Question
Title: What does "Argument #1 is not an array in _form_set_class()" mean?
In Drupal 7, I'm getting this error and want to fix it:

> * Warning: array\_merge() \[function.array-merge\]: Argument #1 is not an array in \_form\_set\_class() (line 4021 of {my site}/includes/form.inc).
> * Warning: array\_merge() \[function.array-merge\]: Argument #1 is not an array in \_form\_set\_class() (line 4021 of {my site}/includes/form.inc).
> * Warning: implode() \[function.implode\]: Invalid arguments passed in theme\_radios() (line 2746 of {my site}/includes/form.inc).

What does this mean, and what should I do about it?

# Answer
For me it happened; when I used

`$form['field']['#attributes'] = array('class' => 'myclass');`

While it should be

`$form['field']['#attributes'] = array('class' => array('myclass'));`
> 10 votes

# Answer
There's likely a buggy FAPI definition. Are you developing a form? If so, check your form definition. It's not being returned as an array.
> 1 votes

# Answer
So i figured it out, I wasn't sure what I had done to make this start happening, but it was being caused by the "Drupal for Facebook" module. It was only popping up when I was on a node edit page strangely. For those familiar, I had the "FB User Management" enabled and after disabling, it stopped giving me the error.
> 0 votes

---
Tags: 7
---


# Question
Title: translate custom fields in the registration form
I've installed i18n and added some new fields to the registration form, but I can't translate these new fields.

If I create a view to list the registered users, the string I want to translate shows up in the Translate Interface, but it only works on that page with the users list. The registration form remains untranslated.

I am using Drupal 7.

# Answer
> 3 votes
You need the i18n\_field module from http://drupal.org/project/i18n. This allows to translate field labels, descriptions and so on.

# Answer
> 0 votes
The core field translation utilities has no user interface, so you'll need the Entity Translation module.

After installing and enabling it (which also enables translation and locale modules), you may need to run update.php.

---
Tags: entities, i18n-l10n
---


title: VBO or Administration Views problems

text:
# Question
Title: VBO or Administration Views problems
It's difficult for me to judge which module is at fault, but since I enabled Administration Views to be able to filter content by name, actions stopped working. For example:

1. **Publish selected content** gives a confirmation message that the operation was successful but the content remains unpublished.
2. **Change author** lets me select a user and then displays a confirmation message but the author remains unchanged.

Recently I have also opened an issue for the Deploy module, where the action items "Add/remove to deployment plan" did not show up until I disabled Administration Views.

Is there any secret to successfully operating those modules? (I cannot look up the issues right now as the site seems to be temporarily down).

**Module Versions**

# Answer
> 0 votes
The problem was that by default the Bulk Operations actions are set to enqueue rather than be fired directly.

---
Tags: views
---


# Question
Title: Facebook share in drupal7 sharethis module picking wrong thumbnail image
I using ShareThis module in a drupal7 website for a certain content type say 'news'. When a user hits a Facebook share button, the title and links are fetched correctly but the thumbnail image it chooses is wrong. I want my fbshare to pick my news image as its thumbnail image. Pls help.

thanks.

Update: i got it worked using MPD's comment. i explicitly added og:image in my header. Below is my code. Hope it helps someone.

```
$element = array(
            '#tag' => 'meta',
            '#attributes' => array(
                 "property" => "og:image",
                 "content" => $imagePath,
                  ),
            );
drupal_add_html_head($element,'fb_share_image');

```

# Answer
> 5 votes
Did you test the page with the Facebook Debugger? Remember that Facebook caches page info, so changes don't appear immediately. A side effect of the debugger is that it clears the cache when you test a URL, so changes get picked up.

If you wan to use a specific image, you need to be sure it explicitly has an `og:image` element in the header. I am pretty sure this is something that the Meta Tags module can do this for you.

---
Tags: social-network
---


# Question
Title: how to adjust size of an existing field through api in hook_update?
I have a textfield that is part of a field-collection belonging to a content type made in a custom module. I am looking for a way to expand the size of the field on the update hook of my module.

I've tried the following:

```
function spelersfiche_update_7200() {
  field_update_field(array(
    'field_name' => 'spelersfiche_va_antwoord',
    'cardinality' => '1',
    'type' => 'text',
    'settings' => array(
      'max_length' => '511',
    )
  ));
}

```

In this the max\_length setting has been increased. When i try to run the update for my module i get the following error:

```
The following updates returned messages
spelersfiche module
Update #7200

Failed: FieldUpdateForbiddenException: field_sql_storage cannot change the schema for an existing field with data. in field_sql_storage_field_update_forbid() (line 229 of D:\drupal\volley3\modules\field\modules\field_sql_storage\field_sql_storage.module).

```

From what i understand it says i can't change this setting for a field that contains data. But in my case it's just to make the field larger, so any previously contained data should still be able to fit into the field.

Is there any way around this, because uninstalling and reinstalling is what i was trying to avoid since that will delete all the data contained in the field.

# Answer
> 8 votes
If you want to get around the restrictions imposed by the FieldAPI, and you're positive the change won't cause any data loss, you could just do it manually:

```
$field_name = 'spelersfiche_va_antwoord';

// Get the current settings
$result = db_query('SELECT data FROM {field_config} WHERE field_name = :name', array(':name' => $field_name))->fetchField();

// Change the settings
$data = unserialize($result);
$data['settings']['max_length'] = '511';

// Write settings back to the database.
db_update('field_config')
  ->fields(array('data' => serialize($data)))
  ->condition('field_name', $field_name)
  ->execute();

// Update the value column in both the _data and _revision tables for the field
$new_field = array('type' => 'varchar', 'length' => 511);
$col_name = $field_name . '_value';

db_change_field("field_data_$field_name", $col_name, $col_name, $new_field);
db_change_field("field_revision_$field_name", $col_name, $col_name, $new_field);

// Flush the caches
drupal_flush_all_caches();

```

---
Tags: hooks, updating, entities
---


title: how to retrieve date in computed field

text:
# Question
Title: how to retrieve date in computed field
How to retrieve date from a date field and store it in computed field? I have tried this code:

```
$start_date = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_start_date')));
$entity_field[1]['value'] = $start_date;

```

But it displays 'datetime'. I want to retrieve the value.

# Answer
> 1 votes
It looks like you're indiscriminately popping values off of the array returned from `field_get_items`, without checking to see which index you actually need. I haven't tested this but I think you'll have better luck with code like this:

```
$items = field_get_items($entity_type, $entity, 'field_start_date');

// Use array_shift if you want the FIRST field item
$item = array_shift($items);
// OR
// Use array_pop if you want the LAST field item
$item = array_pop($items);

// Get the date value of the field
$start_date = $item['value'];

// Use start date
$entity_field[1]['value'] = $start_date;

```

---
Tags: 7, datetime, entities
---


# Question
Title: How to display an HTML table after the form submission on the same page as the form?
I am trying to build a form which takes the food item and the no. of servings and calculates the total calories for that particular food and displays it to the user.

User, can add another food by filling out the form again and the calculated calories for the second food is added to the first and the total calories are also displayed. He can add as many food items as he wants and the form shows the total calories of all those food items.

I want to display this information to user in a table. table will have the following columns.. food item, servings, calories and in the last row the total calories of all those food items. I also want to have a another column with a "delete" button to delete that particular food item from the table and refresh the table without that particular food item.

The main problem am facing is, How can I show this table on the same page as that of the form ?

I have been saving all the user submitted info in session variables and I am being able to create and show such table on another page (for example, when user adds many food items and clicks "Done" button, its redirected to another page and the table is shown there.) But I dont want the user to be redirected. I mean if he wants to add another food item to the table, he has to navigate to the form page again and that's not convenient to the user.

To learn how to write forms, I followed this guide, http://drupal.org/node/262422. So my form is in a file, say..myform.module. Now, I have all the data to create an HTML table (Am saving all the food details given by the user in session variables), but how can I make it displayed on the same page as that of the form ?

or in other words, path to my form is, http://localhost/d7/?q=calorie\_consume , I also want the table to be showed on the same path or page. How can I do it?

Where should I put the code for creating the table inside myform.module file ?

So how can I achieve this ? Or is there some other approach to creating such calculators that am not aware of ?

Thanks in advance.

# Answer
> 4 votes
If you're saving your data in `$_SESSION` vars, I think the easiest way would be to check for the existence of your session data when you build up the form. Then you can show the table at the top of the form if the user has already submitted data, and the normal part of the input form directly underneath. A basic example:

```
function my_form($form, &$form_state) {
  if (isset($_SESSION['my_var'])) {
    $form['table'] = array(
      '#markup' => 'Your table markup based on session data here'
    );
  }

  $form['input'] = array(
    '#type' => 'textfield',
    '#title' => 'Title'
  );

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

function my_form_submit($form, &$form_state) {
  $_SESSION['my_var'][] = $form_state['values']['input'];

  $form_state['rebuild'] = TRUE;
}

```

You'll probably need to put some sort of mechanism to clear that session var at some point, if you want users to be able to reset their submission.

A more complete example with functionality to remove items:

```
function MYMODULE_form($form, &$form_state) {
  // If we have some session data set, build a table
  if (isset($_SESSION['MYMODULE_data'])) {
    $header = array('Food', 'Calories');
    $options = array();
    $total = 0;
    foreach ($_SESSION['MYMODULE_data'] as $item) {
      $options[$item['identifier']] = array(
        $item['food'],
        $item['calories']
      );

      // Keep a running total
      $total += $item['calories'];
    }

    // Add the total row
    $options[] = array('Total calories', $total);

    $form['existing_data'] = array(
      '#type' => 'tableselect',
      '#options' => $options,
      '#header' => $header
    );

    $form['remove_item'] = array(
      '#type' => 'submit',
      '#value' => 'Remove Selected',
      '#submit' => 'MYMODULE_form_remove_item'
    );
  }

  $form['food'] = array(
    '#type' => 'textfield',
    '#title' => 'Food'
  );

  $form['calories'] = array(
    '#type' => 'textfield',
    '#title' => 'Calories'
  );

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

  return $form;
}

function MYMODULE_form_remove_item($form, &$form_state) {
  $remove = array_filter($form_state['values']['existing_data']);
  foreach ($remove as $key) {
    unset($_SESSION['MYMODULE_data'][$key]);
  }
  $form_state['rebuild'] = TRUE;
}

function my_form_submit($form, &$form_state) {
  // this example will just use the food name as the identifier
  $_SESSION['MYMODULE_data'][] = array(
    'identifier' => $form_state['values']['food'],
    'food' => $form_state['values']['food'],
    'calories' => $form_state['values']['calories']
  );

  $form_state['rebuild'] = TRUE;
}

```

I haven't tested that but it should give you a good starting point even if there are a few bugs.

---
Tags: 7, forms
---


title: Custom filter for Profile2 data

text:
# Question
Title: Custom filter for Profile2 data
I have to develop a drupal site that allows authenticated users to create personal profiles with data such as interests, personal details, educations, etc.

I created a profile2 type with all needed fields and organize the view of the data with views3. I want to create a filter (search form) that allows other users and visitors to search the name (first- and last name in one "name" single textfield, an OR'ed query), the city, a proximity field as an addt. option if the zip code is entered (by probably using the location module) and also an additional field that searches thru various other profile fields in one single textfield (all fields OR'ed).

For that reason I thought it might be a good idea to create a views custom filter to build such search form and sql queries. I can not find any way using the regular filter criteria such the way I want it described above. For example, I do not get a single textfield for the OR'ed name query, etc.

The code skeleton I have up to now does not generate any filter entry in the criteria dialog at all. The filter modue is enabled in the modules section. I have the strong feeling that the "hook\_views\_data()" is not defined the right way for "profile2 fields". I been looking at various filter examples, but found nothing profile2 data related.

Here is what I have up to now .. like said, just a skeleton I try to work out step by step.

xconsultantview.info

```
; $Id$
name = XConsultantView
description = Custom consultant filter
version = 7.x-1.x-dev
core = 7.x
dependencies[] = views
files[] = xconsultantview_handler_filter_profile.inc

```

xconsultantview.module

```
<?php

/**
 *
 */
function xconsultantview_views_api() {
    return array(
        'api' => 3,
        'path' => drupal_get_path('module', 'xconsultantview')
    );
}
?>
```

xconsultantview.views.inc

```
<?php

function xconsultantview_views_data() {
    $data = array();

    // consultant filter
    $data['node']['consultant_search_filter'] = array(
        'group' => t('Custom'),
        'title' => t('Eliteberater specific consultant filter'),
        'help' => t('Filter consultants on specific fields'),
        'filter' => array(
            'handler' => 'xconsultantview_handler_filter_view'
        ),
    );
?>
```

xconsultantview\_handler\_filter\_view.inc

```
<?php
class xconsultantview_handler_filter_view extends views_handler_filter {

    function options_form(&$form, &$form_state) {
        parent::options_form($form, $form_state);
        // ...
    }

    function value_form(&$form, &$form_state) {
                // not quiet sure if this is needed here
        $form['xconsultantview']  = array(
            '#type' => 'textfield',
            '#title' => t('Term Name'),
            '#default_value' => NULL
        );

        return $form;
    }

    function expose_form(&$form, &$form_state) {
                // seems like here I should define my complete form
                // ...
    }

    function query() {
        $this->ensure_my_table();
                // ... sql query ...
    }

};
?>
```

As I already found out the hook\_views\_handlers() is no more needed in D7, because the include files are defined via the files\[\] in the module info file.

Can anybody shed some light on my question, if such custom filter in general is possible at all or if there are other more simpler solutions. My main problem of understanding lies in the hook\_views\_data() fct and the profile2 fields or if I have to define a subset of the profile2 fields, at least the ones that I need to filter.

Is there any example with an custom filter filtering profile2 fields in a view?

It is my first drupal project, so my in-depth knowledge at this time is quiet limited...

Thanks so much in advance for your help!

# Answer
Use the Search API module with Views to accomplish this functionality. Here is an example.
> 1 votes

---
Tags: 7, views, users
---


# Question
Title: On logout as admin, PHP code from node pages is executed.
When I log out from site as Admin, PHP code in the node pages is being executed. For testing, I had put *node access rebuild* function in one of pages and the site went slow after that. When I checked in the xdebug profiler scripts, I came across this `eval()` call. Is it the default functionality or is it some of my code that has affected this?

# Answer
If the page you are referring is a node page, then the node could be using the PHP input format, and in that case the node body would be passed to `eval()` through drupal\_eval().
If the page is a view page, the Views module allows the administrator users to enter PHP code that is executed, through `drupal_eval()`, in specific circumstances.

In both the cases, a block visible in the page could be using PHP code to set it block visibility.

There could be other modules that call `drupal_eval()`. Those modules pass to `drupal_eval()` code that users with the right permission enter in the module's settings; if you have one of those modules, you should remember ending PHP code in a text area.
> 0 votes

---
Tags: 6, users
---


title: Variables dump to Javascript console

text:
# Question
Title: Variables dump to Javascript console
Is there any equivalent of `var_export` or `var_dump` available in Drupal, that would output variables directly to the `console` object (FF, Chrome - `console.log()` or `console.info()`)? I just don't feel like turning Devel & Themer stuff on and off every time I want to peek into variables...

# Answer
> 5 votes
The Drupal for Firebug module (which can be used with Chrome or Firefox) has a `firep()` function built in which will log a `print_r` of any variable passed to it into the Drupal for Firebug widget. That might be an option.

If you really want a console log, though, I think you'd have to write the functionality yourself. It isn't too hard though, here's a quick module I knocked up that works well for me:

File: js\_debug.info

```
name = JS Debug
core = 7.x

```

File: js\_debug.module

```
function js_debug_log($var = NULL) {
  $log = &drupal_static(__FUNCTION__, array());

  if ($var) {
    $log[] = $var;
  }

  return $log;
}

function js_debug_page_alter(&$page) {
  drupal_add_js(drupal_get_path('module', 'js_debug') . '/js_debug.js', 'file');
  drupal_add_js(array('js_debug' => array('messages' => js_debug_log())), 'setting');
}

```

File: js\_debug.js

```
(function($) {
  $(function() {
    if (Drupal.settings.js_debug.messages) {
      for (var i = 0; i < Drupal.settings.js_debug.messages.length; i++) {
        console.log(Drupal.settings.js_debug.messages[i]);
      }
    }
  });
})(jQuery);

```

The above code is obviously very bare, and doesn't check to make sure `console.log()` is available, etc. But it will work fine in Chrome/Firefox for any var (including arrays and objects).

To use, simply call `js_debug_log($var);` from code; the variable you pass will be logged in the console as you'd expect.

---
Tags: javascript, debugging
---


# Question
Title: Drupal behaviour function not getting executed
I defined a simple block on my module, using the following code.

```
function visita_virtual_block_view($delta = '') {
  switch ($delta) {
    case 'mapa':
      $path = drupal_get_path('module','visita_virtual');
      drupal_add_js('https://maps.google.com/maps/api/js?sensor=false','external');
      drupal_add_js($path.'/visitavirtual.js');
      $block['subject'] = t('google maps');
      $block['content'] = visita_virtual_mapa_content();
      return $block;
  }
}

```

That returns a simple div with an specific id, wich will allow me to alter it later through the usage of the google maps api. For that I defined my 'visitavirtual.js' file, and inside of it I declared the Drupal behavior. That function is supposed to get executed when the whole page is loaded, since it'as a wrapper of the JQuery ready function.

```
(function($){
  Drupal.behaviours.visita_virtual = {
    attach: function(context,settings) {
      alert('Entered the init function');
      var latlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    }
  };
})(JQuery);

```

However, that code is not executed; I can't even see the alert window. What am I doing wrong?

# Answer
Lol, it was a silly typo, Sorry. First it's behaviors not behaviours and then the namespace is jQuery not JQuery. Hard to find them on the IDE since it's valid javascript after all.
> 4 votes

---
Tags: blocks, javascript
---