title: Probem with formatting fields

text:
# Question
Title: Probem with formatting fields
Two questions that I guess are both a part of one bigger idea. When creating a content type, I've been trying to figure out how to both indent a field and create a line break after a field both by default. For indenting I have tried adding spaces before the field name, but because it's empty space they are disregarded and displayed as normal. For the line break, I've tried adding a custom code field with br or p, and simply adding a blank field, but in both situations as there is no text to display, the field is not displayed at all. Any suggestions?

# Answer
> 1 votes
The safest thing to do is to use the `#attributes` Form Control Attribute. You can specify a CSS class to target this element to then supply some css rules to indent these elements in your sites theme.

Similarly, you can add a class to add a line break somewhere within the widget markup to create your linebreak. Be sure to notice that the class example in the linked documentation takes a PHP array of class(es) (not a string label for the class) ... that messed me up last week for like 20 minutes.

---
Tags: entities
---


# Question
Title: Trying to override Drupal core 'find content' with a view and VBO
I am trying to replace the core content admin area with a view and VBO. I managed to create the view and have it override admin/content/node without an issue. However the administer content area is also accessible by admin/content. I tried creating a second view to override it but it breaks the menu. It appears to be a menu router issue. Any thoughts on how to overcome this (other than adding a redirect)?

# Answer
> 1 votes
Views doesn't really know how to override paths. It always breaks menus. You need the Admin Views module that provides some extra code for overriding to work.

# Answer
> 0 votes
You should look into the Contextual Administration module. You can use it to easily recreate the same kind of 'find content' page with VBO and it's pretty flexible.

As for your current approach, I haven't looked into it too much but I'd think a redirect may be your best bet.

---
Tags: 7, views
---


title: Omega theme in IE 9

text:
# Question
Title: Omega theme in IE 9
I installed the "Omega" theme on my local server. Looks just what I needed! Responsive webdesign in just a few minutes.

When you take a look at the Omega Micro-site, you will see that everything works great, also in IE9. But when I installed the template on my server it doesn't work in IE9... I always see the template with largest grid loaded.

# Answer
If your press F12 in IE9 to bring up the developer tools, what are Browser Mode and Document Mode set to? If they are not IE9, trying changing the settings to IE9 to see if responsiveness then works.

You might look at Tools-\>Compatibility View settings. See if "Display intranet sites in Compability View" is checked. Try unchecking this and refreshing.
> 1 votes

# Answer
Do you have CSS aggregation switched on on your local server? IE has like 31 CSS file limits. Still not fixed in IE9
> 0 votes

# Answer
Not sure what exactly is not working but if the page is wider than 940px + 20px as you would expect, than need to check your theme settings \> grid settings and uncheck the wider/fluid/narrow if you need a fulltime fixed width.

Make sure your primary layout is normal. The primary layout will be used in case you disable the "responsive grid" option as well as for older versions of Internet Explorer.
> 0 votes

---
Tags: 7, theming
---


title: Media + WYSIWYG or ICME + CKeditor

text:
# Question
Title: Media + WYSIWYG or ICME + CKeditor
I need to build quite feature rich set of tools for file & media management both for embedded and stored files in a new D7 project. Media will be added to both fields and in the WYSIWYG and File manager is a must.

In the past I have always been working with a combo of CKeditor, IMCE, CKeditor Link, FileField Sources.

However there seems to be a lot of buzz around TinyMCE via the WYSIWYG module and Media modules. In short what am I missing out on with these new projects? They seem to have a big overlap on the above and was wondering if people have experience with both...

Should I be looking to change my toolset to WYSIWYG / Media combo?

# Answer
> 1 votes
Pantheon is now offering Panoply, a distribution built on Panels that features TinyMCE via WYSIWYG as well as the media module already set up and ready to go. You can register for a free account with them and test out a pre-built version of Drupal with the modules already set up in a fairly intelligent configuration.

Disclaimer: I'm a Pantheon customer, but I really do think that trying out this distro is a great way to see a hands-on example of what can be done not just upon installing a bunch of modules but after someone has taken the time to polish up the site.

# Answer
> -2 votes
I see no inconvenient in using WYSIWYG rather than install TinyMCE by hand. TinyMCE and CKEditor are the only which support IMCE integration using IMCE Bridge module. You should use these 4:

* WYSIWIG module
* TinyMCE or CKEditor
* IMCE
* IMCE Bridge

---
Tags: 7, wysiwyg, media, files
---


# Question
Title: How to prevent the addition of HTML in "Full HTML" text format?
Sometimes, Drupal has the annoying habit to automatically add HTML to the content's source, generally `<br/>` and `<p>`, even when the text format is set to "Full HTML".

This is really annoying and I can't find any way to prevent that. Any idea ?

# Answer
> 7 votes
Ok, I think I've found the answer:

This is a "feature" of the Full HTML mode.

> Full HTML:
>
> * Web page addresses and e-mail addresses turn into links automatically.
> * Lines and paragraphs are automatically recognized. The
> line break,
>
> paragraph and
>
> close paragraph tags are inserted automatically. If paragraphs are not recognized simply add a couple blank lines.

You can disable it in You are here `Administration » Configuration » Content authoring » Text formats` by unchecking `Convert line breaks into HTML (i.e. <br> and <p>)`.

Source: http://drupal.org/node/503754

# Answer
> 2 votes
It depends on the configuration of the filters the input format uses.

You can disable the tags you're talking about on the page : http://yoursite/admin/config/content/formats/full\_html.

Just uncheck `Convert line breaks into HTML (i.e. <br> and <p>)`.

---
Tags: 7
---


# Question
Title: how to display a link on a node view page?
I want to display a link on a node view page just like the "Add new comment" link. How should I do this?

I think it can be done through `hook_node_view()`, but how can I use this hook?

# Answer
In your implementation of hook\_node\_view(), add an element to the `$node->content` array. The element should be a renderable array as expected by drupal\_render().
> 1 votes

# Answer
In drupal6, you could implement the hook\_links (just like the node module does http://api.drupal.org/api/drupal/modules--node--node.module/function/node\_link/6)
> 1 votes

# Answer
Use `hook_node_view` and add new variable `$node->my_link` , add template file page--my\_node.tpl.php and place that link wherever you want. This is solution for dynamic link for every node.

If you just want to add some no-dynamic link to your node\_type than just add it in template file.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to run PHP code only once on node creation?
I'm using Drupal 7, and the Computed Field module.
I want to run code just once, when the node is created.

Is there any specific function?

# Answer
If you want to run code just once when a node is created, the Rules module may be a better choice.

Using Rules, you can do the following:

1. Create a new rule that acts on the event "After saving new content."
2. As the action, "Set a data value" and target the field you want to modify (this would be a standard field rather than a computed field in this case).
3. As the "Value", input your PHP code in php tags.

This way the code will be evaluated only once.
> 6 votes

# Answer
Have a look at hook\_node\_insert

For how to use it have a look at book\_node\_insert, but you can access any field you want: $node-\>title contains the title and for fields it's something like $node-\>field\_myfield\[0\]\['value'\] (a text field called myfield).

The easy way is to install devel and add dpm($node) inside your function.
> 1 votes

---
Tags: entities
---


title: project version/revision module

text:
# Question
Title: project version/revision module
I'm in search of a module (or technique) to keep track of the software/release version that a Drupal installation is running. I am not talking about the Drupal version running the site (e.g 7.12) but of the implemented site itself, exactly like any Stack Exchange site does on the footer (currently: **rev 2012.4.5.2127**).

I need a structured way to keep track of this data (so a plain text block on the footer will not do) because I'll need to access this information from other systems as well.

Currently I've solved it by using a persistent variable that I handle with Drush.

```
# Set it.
drush vset --always-set release "1.0.4"

# Get it.
drush vget release

```

Is there another (probably better) way of handling this?

# Answer
As part of your build script and/or revision control checkin script, write out a version number to constant in an include file. Write a custom module that does something with this include file, such as make a block that prints it out, stuffs it into `$conf` expose the value via webservice, etc. You could also do this directly to `settings.php`, too, if you just need a variable.
> 2 votes

---
Tags: 7
---


title: Add AJAX popup multistep form

text:
# Question
Title: Add AJAX popup multistep form
I am trying to build an AJAX popup for my custom built multi-step form using the form API. I have examined the module "Modal forms" and wondering if i should use that module or just create the AJAX functionality from scratch. Could someone one please give me an example of how I can add AJAX popup functionality to my form?

Here is an illustration of what I would like to achieve:

I have been looking at the Chaos tool suite module example:

```
ctools_include('ajax');
ctools_include('modal');

// Add CTools' javascript to the page.
ctools_modal_add_js();

// Create our own javascript that will be used to theme a modal.

```

I have found this code snippet. I am trying to get it to work in my module.

Here is the code I found

```
function redirect_custom_reg_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array(
      'redirect_custom_reg_user_register_form'
    );
  }
}

function redirect_custom_reg_user_register_form() {
  $form = array();
  // Add the form fields for the registration form.
  // ....
  $form['name']['formtype'] = array(
    '#type' => 'radios',
    '#title' => t('form type'),
    '#options' => array(
       t('one form'),
       t('two form'),
       t('three form')
    ),
  );

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

  return $form;
}

function redirect_custom_reg_user_register_form_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. personal="@username"', array('@username' => $form_state['values']['username'])));
}

```

Here is the code from the modal example in Chaos tool suite module:

```
switch ($option) {
  case 0:
    drupal_set_message('patient');
    $form_state['redirect'] = 'patient/form';
    break;

  case 1:
    drupal_set_message('student');
    break;

  case 2:
    drupal_set_message('doctor');
    break;
}

```

Here is the example from the Chaos tools which creates a custom modal display:

Here is the code that I have extracted from the tutorial. From the comment this seems to be used to theme the custom modal:

```
function ctools_ajax_sample_page() {
  $sample_style = array(
    'ctools-sample-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 500,
        'height' => 400,
        'addWidth' => 20,
        'addHeight' => 15
      ),
      'modalOptions' => array(
        'opacity' => .5,
        'background-color' => '#246'
      ),
      'animation' => 'fadeIn',
      'modalTheme' => 'CToolsSampleModal',
      'throbber' => theme('image', array(
        'path' => ctools_image_path('ajax-loader.gif', 'ctools_ajax_sample'),
        'alt' => t('Loading...'),
        'title' => t('Loading')
      )),
    ),
  );

  drupal_add_js($sample_style, 'setting');

  // .....................
  // .....................

  // This displays the widget.
  $button_form  = ctools_ajax_sample_ajax_button_form();
  $links[] = l(t('Wizard (no modal)'), 'ctools_ajax_sample/nojs/animal');
  $links[] = ctools_modal_text_button(t('Wizard (default modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'));
  // .....................
  // .....................
}

```

# Answer
Here is the answer to my question by using the chaos tools:

```
// this creates the url that can be entered to reach this form
function ctools_ajax_sample_menu() {
  $items['ctools_ajax_sample/simple_form'] = array(
    'title' => 'Simple Form',
    'page callback' => 'regone_form',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

function regone_form() {
  global $user;

  ctools_include('ajax');
  ctools_include('modal');

  // Add Ctools' JavaScript to the page.
  ctools_modal_add_js();

  $sample_style = array(
    'ctools-sample-style' => array(
      'modalSize' => array(
        'type' => 'fixed',
        'width' => 500,
        'height' => 400,
        'addWidth' => 20,
        'addHeight' => 15
      ),
      'modalOptions' => array(
        'opacity' => .5,
        'background-color' => '#246'
      ),
      'animation' => 'fadeIn',
      'modalTheme' => 'CToolsSampleModal',
      'throbber' => theme('image', array(
        'path' => ctools_image_path('ajax-loader.gif', 'ctools_ajax_sample'),
        'alt' => t('Loading...'),
        'title' => t('Loading')
      )),
    ),
  );

  drupal_add_js($sample_style, 'setting');

  ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
  ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');

  $links = array();
  $links[] = ctools_modal_text_button(t('Wizard (custom alex modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'), 'ctools-modal-ctools-sample-style');

  $output  = theme('item_list', array('items' => $links, 'title' => t('Actions')));

  // This deals with theming of the modal box.
  $output .= theme('ctools_ajax_sample_container', array('content' => '<h1>' . t('Sample Content') . '</h1>'));

  return array('markup' => array('#markup' => $output));
}

```
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: What is the correct way to create a translatable in four languages website logo with slogan?
What is the correct way to create a translatable in four languages website logo with slogan? I am thinking of creating a custom content type which will be populated in View block. Which when will be inserted in logo region. Are there any other approaches?

# Answer
> 5 votes
Are you already using the i18n module? The package contains the 'Variable translation' module which allows you to make certain variables language dependent. Since the site logo is also stored in the variables (`theme_settings['logo_path']` if I'm not mistaken) you can make that variable language dependent as well.

If you're not using the i18n module (and you're not going to need it soon), I suppose you can also switch between logo images in your theme's template.php.

I wouldn't recommend creating a node type for it. In my experience, whenever you're considering to create a node type that is meant to have a specific number of nodes, there probably is a better solution for what you're doing.

---
Tags: 7, media
---


# Question
Title: When using the boxes module, is it possible to export the region and visibility settings?
I just installed the Boxes module and I added a box to my feature. The box description and body were exported successfully, but the region settings (where in the theme(s) the box appears) and the visibility settings (show block on specific pages, etc.) were not.

How can I export the placement information for boxes as well?

# Answer
Ah, I just realized there is an issue for this in the boxes queue. As of May 2012, the issue has been resolved and this is now possible.
> 0 votes

---
Tags: 7, blocks
---


title: CCK checkboxes with no labels

text:
# Question
Title: CCK checkboxes with no labels
I'm currently creating a form where the user is supposed to check a (sometimes large) number of checkboxes. The problem is that I only want the checkboxes visible, not their label (or key) while the user is filling out the form. Is this possible?

Currently it looks like this:

\[ \] label \[ \] label \[ \] label etc.

I'm aiming for:

\[ \] \[ \] \[ \] ... \[ \]

I'm using Drupal 6.22 with CCK 6.x-2.9. Other related modules in my form that will interact with the checkboxes are Conditional Fields 6.x-2.0 and Multicolumn checkboxes/radios 6.x-1.6

Any help is appreciated. Thanks in advance.

# Answer
you can use visibility:hidden; (and height and/or width 0px). I use visibility:hidden; when display:none is not useful (issues of inheritances of CSS, or maybe still you can need the values of the hidden elements).

Other suggestion. I have several forms that use lots of checkboxes, so I use Vertical Tabs http://drupal.org/project/vertical\_tabs to divide the forms in several tabs, to show only one group of checkboxes per tab. So here is not necessary to remove labels of checkboxes.
> 2 votes

# Answer
Probably the wrong way to do it, but I found the labels go away if you uncheck the Use field label instead of the "On value" as label in the Content Types-\>Fields dialog.
> 1 votes

# Answer
If you just need to hide the label you could probably target it with CSS and display:none;. It's probably one of these classes: .field-label .field-label-inline .field-label-inline-first. You can check out the template files in the cck themes folder if you want to modify the behavior.

Template: \[modules folder\]/cck/theme/content-field.tpl.php

Another helpful resource is hook\_form\_alter but with CCK you will want to review the #after\_build option. This page discusses how to alter cck elements. http://drupal.org/node/726282
> 0 votes

---
Tags: entities
---


title: Show a boolean as a pair of images?

text:
# Question
Title: Show a boolean as a pair of images?
I have PictureEvents and those have a few boolean fields:

```
HasCD | HasDVD | HasSlowMo

```

I'd like to have an icon for each of them that is dim/bright in all the places where it's shown (I have a few Field-Views for the lists of PicutureEvents, and I'd like to place the icons below the video in the main page).

Where do you do this in Drupal 7?

# Answer
Easiest way to do this would be in a content-type template. You want to create a template for your content type, ex. node--\[type|nodeid\].tpl.php and add this in your theme folder. In your template, for displaying the boolean field you could use logic like this:

```
<?php
if ($node->field_boolean_field[$node->language][0]['safe_value'] == 0) {
    print "<img src='no_img.jpg'>";
} else {
    print "<img src='yes_img.jpg'>";
}
?>

```

This similar question may help as well:

Optionally add image/icon after node title based on boolean content type field?
> 1 votes

---
Tags: 7, views, entities
---


# Question
Title: node_overview_types no hook? how to customize
Ok, i'm finally starting to understand how to use hooks! I am trying to customize the table that appears on `admin/structure/types` I would like to add a custom link between `manage fields` and `manage display`. I have tracked the creation of this down to the `node_overview_types` function in content\_types.inc. I did not see any hooks like hook\_theme\_table. My initial response was to look for a hook\_table\_alter but I did not see one in the drupal api. Any help would be appreciated.

# Answer
> 1 votes
Since there's no specific theme function used the easiest way I can think of is to implement `hook_page_alter()` and alter the table directly. The following code works for me:

```
function MYMODULE_page_alter(&$page) {
  if (request_path() == 'admin/structure/types') {
    // Get the types, they will automatically be in the same order as the rows
    // in the existing table
    $types = array_keys(node_type_get_types());
    $limit = count($types);

    for ($i = 0; $i < $limit; $i++) {
      // Get the existing row
      $row = $page['content']['system_main']['node_table']['#rows'][$i];

      // Get the type related to this row
      $type = $types[$i];

      // Make a link to add to the table
      $link = l('Link Text', 'my/path/to/' . $type);

      // Make up the new cell. I know there's an easier way to do this but
      // I can't for the life of me remember it right now
      $new_row = array($row[0], $row[1], $row[2], $link, $row[3], $row[4]);

      // Overwrite the existing row with the new one
      $page['content']['system_main']['node_table']['#rows'][$i] = $new_row;
    }

    // Increase the colspan of the header to take into account the new column
    $page['content']['system_main']['node_table']['#header'][1]['colspan'] = 5;
  }
}

```

---
Tags: 7, hooks, nodes
---


title: How can I join two tables?

text:
# Question
Title: How can I join two tables?
I have a database table whose schema is the following one.

```
$schema['location'] = array(
  'descritiption' => 'location',
  'fields' => array(
    'locationID' =>  array(
      'description' => 'primary key for patients table',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE),
    ),
    'addressone' => array (
      'description'    => 'this shows the first line of the address',
      'type'         => 'TEXT'
    ),
    'county' => array(
      'description' => 'this is a county list'
    ),
    'postcode' => array(
      'description' => 'stores the postcode'
    ),
    'primary_key' => array('locationID')
  )
);

```

How would I join this table with the user table?

# Answer
`JOIN`s are a query-level concept and don't really make a lot sense in the context of a schema definition.

I suspect what you're asking is how to add a foreign key from your `location` table to the `users` table. If so I'm afraid you're out of luck; Drupal does not enforce foreign key relationships, so you'll need to define and maintain your relationships at a code level.

There is a `foreign keys` property that can be applied to tables defined by the schema API, but it is for documentation purposes only, no foreign keys are ever added at the database level.

Just in case you are asking how to join a table in a query:

```
$query = db_select('location', 'l')
  ->fields('l');

$query->join('users', 'u', 'u.uid = l.uid_column_name');

$results = $query->execute();

```
> 3 votes

---
Tags: 7, database
---


# Question
Title: Display ubercart product image given a product nid
How do I display a product's image given the nid?

# Answer
It's tricky without some more information but something like this:

```
$product = node_load($nid);
$image_path = $product->field_image_cache[0]['filepath'];

print theme('imagecache', 'product', $image_path, $product->title, '');

```
> 1 votes

---
Tags: 6, ubercart
---


title: How to reproduce drupal.org search?

text:
# Question
Title: How to reproduce drupal.org search?
I would like to reproduce drupal.org search. I know that is used the Apache Solr module.What I don't know is how to make appear the available selections like Module,Themes,All,Groups etc so as to filter only these. How can I do this? Thanks

# Answer
> 1 votes
This is not so much an issue of suing Apache Solr as it is one of working with the database query system. To do what you want you will have to become very familiar with the Views module. I recommend watching the nodeone.se series 'Taming the Beast'

Views is a UI for making sql queries. You create a view definition with a path you assign to your look-up page. It will include filters to sort content by types. The various categories of information at Drupal.org are basically different content types. The various displays lists etc. used to provide the information can be provided by a variety of modules. I would recommend exploring Panels and Page Manager to provide and display the information. Nodeone.se also has an excellent series called 'Learn Page Manager' that can help you master those issues.

If you want custom functionality and know your way around PHP you may want to look at the Drupal Forms API, the Search module, and Search API module for additional functionality in creating customized searches and forms.

---
Tags: views, search
---


# Question
Title: Drupal 7: Variables in external file access
Im having a tough time accessing variables from my own external file.

I gave this file:

```
?php include_once('/exercise_names.php'); ?
```

Which contains the following:

```
 ?php

//Exercise Names

$memory01 = '1';
$memory02 = '2';
$memory03 = '3';
$memory04 = '4';

?
```

I cannot get the page to render the names. I keep getting the following errors:

Notice: Undefined variable: memory01 in eval() (line 4 of /home/webapps/drupal/releases/modules/php/php.module(80) : eval()'d code).

Basically its telling me it cant find the required variables, but they are in the file. For some reason it cannot read the included file.

Any ideas?

thanks, Mac

# Answer
If I have a module called `foo`, I put all of my includes in a subdirectory called 'inc/' and then use this

```
<?php

require_once(dirname(__FILE__) . "/inc/constants.inc");
require_once(dirname(__FILE__) . "/inc/class.FOO.inc");
require_once(dirname(__FILE__) . "/inc/class.BAR.inc");

```

in `foo.module`. If doing Drupal 7, you may also want to take a look at the files directive for .info files:

> Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file, like so:
>
> ```
> files[] = example.test
>
> ```
>
> When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.

EDIT TO ADDRESS COMMENT

Even if you aren't doing this in a module, you should really abstract out the constants into a module that provides getter functions and/or a static class and/or a singleton with getter functions.

Another option is to bail on includes, and use `variable_set` / `variable_get`, preferably in conjunction with a module settings form.
> 3 votes

---
Tags: 7
---


# Question
Title: How can I programmatically reset a user's password
I have a native mobile application communicate with my drupal 7 site via services module. I'd like to give users the ability to reset their password from the app. Is there a way to initiate this process programmatically, so a an email is generated with a one time use token that expires in 24 hours?

Thanks

# Answer
> 20 votes
You can use the `_user_mail_notify()` function, along with a user object, to invoke the password reset email:

```
// Load a user (admin in this case).
$account = user_load(1);

// Invoke the email. It will be queued along with other system mail to be sent during cron
_user_mail_notify('password_reset', $account);

```

A one time login URL with a 24 hour expiry is included by default with that particular email.

---
Tags: 7, users
---


# Question
Title: How can I secure a custom module that contains sensitive data?
I have made a custom module that contains my backup\_migrate module profiles as described in this post. Inside the array are my keys to log in to Amazon S3, which I certainly want to keep secret.

Putting such data in code inside a module immediately set off an alarm inside my head. Is this a terrible thing to do from a security standpoint? If so, why?

# Answer
As long nobody is able to read this php files, there's no problem. If your host is set-up correctly and you are using the standard .htaccess file which comes with core, you should be fine.

An other question is who has access to your host and your source code. A good practice is to avoid any sensitive data inside git or any other source control system. A way to do this is to have a `local.settings.php` file a longside your `settings.php`. You can include it in your `settings.php` by ading this code at the end of the file:

```
if (file_exists(dirname(__FILE__) . '/local.settings.php')) {
  include(dirname(__FILE__) . '/local.settings.php');
}

```

Make sure this `local.setings.php` file is never visible to unauthorized people.

You can set any system variable in local.settings.php to your needs.
> 7 votes

---
Tags: security
---


title: Why is hook_form_alter() so messy?

text:
# Question
Title: Why is hook_form_alter() so messy?
Here's an example I just ran into. I'm trying to put some HTML in the label of my field.

```
$form['field_feedback']['und']['#title'] <- has the title
$form['field_feedback']['und'][0]['#title'] <- has the title
$form['field_feedback']['und'][0]['value']['#title'] <- has the title. (Works)

```

Why are there three populated #title attributes with only one being used?

# Answer
> 73 votes
What you're seeing is how Drupal represents fields in a form. It breaks down like this:

* The children of the outer array, `$form['field_back']['und']` (`'und'` for `'undefined'`), are the different languages the field has been translated into. In Drupal, you are recommended to use `LANGUAGE_NONE` for `'und'` in code.
* The children inside each language array, e.g. `$form['field_feedback']['und'][0]`, represent the different entries for the field. For example, if a field has unlimited cardinality, and there are several entries for that field, they will show as `$form['field_feedback']['und'][0]`, `$form['field_feedback']['und'][1]`, etc.
* Finally you have the form input element(s), for the field values themselves, e.g. `$form['field_feedback']['und'][0]['value']`. In this case the column name is `value`, for a node reference field type it would be `nid`, and so on. If a field has multiple data columns associated with it you'll see more children as well. These are represented by a text field/select box/special widget, and will ultimately provide the value for the field.

The fact that titles have been added to the various elements throughout the hierarchy is incidental to be honest. Whether or not those titles are displayed on the form is down to the particular settings of the render array in which each `#title` is contained.

To change the title on the actual form widget, you only need to worry about the form element at the very bottom of the array: i.e. the actual input elements (`$form['field_feedback']['und'][0]['value']`, etc.).

It's probably worth noting that the element/widget used for a particular field may be quite complex. If you don't already have it, you should install the Devel module and use the `dpm()` function to inspect the `$form` array; that will show you exactly where in the array the elements you're trying to target are.

---
Tags: 7, forms
---


# Question
Title: Views Block displaying above node content
I created a block using *Views* which is displayed on some particular content. However the block is being displayed before the main content. I tried changing the row weight for the block but this was no use.

All I need is to display the block after the node content.

# Answer
Try out the below images step by step, i believe you are the evolving this step before you do with other `blocks` and `pages`

And see if that

`Show block on specific pages` are in

`All pages except those listed` or

`Only the listed pages`..

Make that to `All pages except those listed` and check that out..
> 4 votes

# Answer
I know you've mentioned that you've tried the row-weights on the block page and it hasn't worked, but this is 100% definitely the correct way to order blocks within regions. For example:

In that example the Search Form comes after the main page content (which is a block in Drupal 7), which includes the node content, for every page on which it's active. I've tried it with blocks made from Views as well and it work exactly as expected.

I guess it's possible that you have some theme preprocessing/template override that might be re-ordering the blocks but I can't imagine why you'd have that and not know about it.

If that's not the case the only thing I can really suggest is check to make sure you don't have any rogue CSS causing that particular block to appear above the node content. It's a long shot but it may be the case.

If you've checked your theme's template.php file and page template files, and the CSS, and it still doesn't work, I can only advise re-installing/overwriting your Drupal core files as it's likely there's something wrong with the one you're currently working with.
> 3 votes

---
Tags: views, blocks, nodes
---


# Question
Title: How can I display an image within a node with an SRC value that incorporates a URL taken from another field?
I'm creating a directory of useful (web based) resources for a community. I'd like to use Drupal 7, but can use Drupal 6 if absolutely necessary. I don't mind installing any additional useful modules.

I'd like to create a node with a link field that stores the URL of the useful resource.

I'd like to display a screenshot of this URL, using WordPress's mshots feature, as part of the node.

So, as an example, the value of the link field would be:

> http://mashable.com/guidebook/twitter/

Within my content type template, or as an image field, or however you suggest I do it, this URL would need to be encoded and inserted into an image SRC value to give:

> http://s.wordpress.com/mshots/v1/http%3A%2F%2Fmashable.com%2Fguidebook%2Ftwitter%2F?w=500

Which shows a 500px wide screenshot of that URL.

What do you think would be the best way of doing this? I could use 'rewrite the output of this field' in Views, but I'd like the screenshot to be shown in the node view too.

# Answer
You could use a custom 'screenshot' formatter for the link field. Further info for D6 and D7.
> 0 votes

---
Tags: views, theming, media, nodes
---


title: Can we override Drupal includes files?

text:
# Question
Title: Can we override Drupal includes files?
I want to modify the menu.inc file that is in the Drupal "includes" folder, but I want to create an overriding file for it, so that we can easily package only our custom theme.

# Answer
Generally Clive is right. Don't touch core. But sometimes you are forced to do a core patch or it's just much easier to solve your requirements.

If you must: I'd recommend to put your whole project into git. This gives you the possibility to have a clean core version in one branch and the patched one in an other. Everytime a new core version is published you can merge it in a clean way.
> 3 votes

---
Tags: 6
---


# Question
Title: How can I render a result row using the Views API
I'm trying to render the rows in a view manually using the Views API. The style plugin is the "Unformatted" plugin. This is my code:

```
<?php
$view = views_get_view('nearme');
$view->execute('default');
$view->preview();

$renderer = $view->style_plugin->row_plugin;
foreach ($view->result as $row) {
  echo $renderer->render($row);
}
?>

```

This code almost works - it renders essentially a blank row. My "Global: custom text" field is rendered, as are some generic labels and field HTML, but the actual values from $view-\>result are not interpolated.

What am I doing wrong?

# Answer
The tokens in views requires $view-\>row\_index to be set to be able to get the right rendered fields.

```
$view = views_get_view('nearme');
$view->execute('default');
$view->preview();

$renderer = $view->style_plugin->row_plugin;
foreach ($view->result as $index => $row) {
  $view->row_index = $index;
  echo $renderer->render($row);
}

```
> 14 votes

---
Tags: views
---


# Question
Title: How do I display user picture from profile fields?
> **Possible Duplicate:**
> How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php?

I would like to display the user pictures in message list and message view. The images are uploaded through a user profile field, and not the default Drupal account picture field.

How do I do this in Drupal 7?

# Answer
Private Message displays the user picture via a theme('user\_picture') so I'd just copy the `user-picture.tpl.php` template out of the system user module directory and into your theme's and modify it to display your field instead of the default. You may want to put additional logic in there so that it doesn't do this everywhere but that's up to you.
> 2 votes

---
Tags: 7, privatemsg
---


# Question
Title: How to use the Charts module for creating charts using Views?
I am using Drupal 6 and trying to setup the Charts module to work with Views.

On the Charts project pages it says

> **Views integration**: Display the Views results as charts

so views is supported. However I had no luck at all so far. Even though the module seems very well written, it lacks documentation.

**My question**: How to set this up?

# Answer
> 1 votes
Here's what I used (running a brand new drupal 6.25 install):

The Charts module comes with a few chart providers (SD Image Chart and Google Charts). You need to enable one of them in the module list to use in views. I enabled Google Charts for this example.

Then, I created a new view. I set the Style option to "Chart". To demo the chart, I just added a Node: Nid field and created some dummy nodes. The chart provider you selected will render the chart in the preview for you. You can configure the Style Plugin settings and the fields to get the kind of chart you want.

---
Tags: views, 6, charts
---


# Question
Title: Do I need to manually destroy the EntityFieldQuery object?
I'm using an EFQ object inside a foreach loop:

```
  //bundle those terms with nodes they each have
  foreach($relevantTerms as $dishType)
  {
    $nodeQuery = new EntityFieldQuery();

    $entities = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'food_menu_item')
      ->propertyCondition('status', 1)
      ->execute();

    $nodes = entity_load('node', array_keys($entities['node']));
    krumo($nodes);
  }

```

After the loop stops executing, am I correct in thinking one instance of $nodeQuery will remain in memory for the rest of the request? Do I need to destroy this using unset() for performance?

# Answer
You shouldn't really have to care about this much. Because PHP will clean up all this stuff at the end of the page's request lifetime. If you really want to cleanup this lingering instance of anything you just `unset()` it as-needed.

Something is fishy with your code as your EFQ is in a loop, but it's not being used in the loop for anything what-so-ever.
> 4 votes

# Answer
PHP objects are automatically destroyed when they go out of scope. In your case:

* If `$nodeQuery` is used only inside the `foreach()` loop, that happens when the loop ends
* If `$nodeQuery` is a local variable used in a function, that happens when the function ends
* If `$nodeQuery` is a global variable, that happens when PHP executes the last instruction in the *index.php* file

Considering that in most of the cases you are using a local variable in a function, and a function doesn't create more than a object of that class to keep its reference in different variables, there isn't any performance issue with letting PHP automatically destroy the object.
> 1 votes

---
Tags: 7, entities
---


title: Organic groups users cant leave groups

text:
# Question
Title: Organic groups users cant leave groups
I cant find a link where I can add for people in a group to be able to leave the group.

back in the older version it was something like og/member/group\_id, but that doesnt work anymore.

I'm using drupal 7 with OG version = "7.x-2.0-alpha2"

# Answer
> 3 votes
It's /og/%/%/unsubscribe. See og\_ui\_unsubscribe() in og\_ui.pages.inc to learn what are the arguments passed onto this.

---
Tags: 7, organic-groups
---


# Question
Title: How to hide Header and footer printed page?
I'm using drupal 7 with print module,when printing some node there is some extra content like (date , pager and url) in the header and footer page that will be printed.
I just want to print the content of the node.
How can i remove this content?

# Answer
You can use module to print a node also to remove unwanted region you can change print.tpl.php inside the module

or you can use css

```
@media print
    {
        #header,.menu_background,.breadcrumb,#comments,#sidebar-first,.footer_bg,.node-links { display: none; }
        .node-view{ display: block;height:800px; }
    }

```
> 1 votes

# Answer
copy sites/all/modules/print/print.tpl.php to your theme directory.

edit print.tpl.php and remove codes expect where main content has been printed:

```
<div class="print-content"><?php print $print['content']; ?></div>

```

save file, clear drupal cache
> 1 votes

---
Tags: theming
---


title: Subtheming to add a single template?

text:
# Question
Title: Subtheming to add a single template?
As a programmer, I know a great deal about Drupals backend functionality, but little about theming. I'm using Corolla as a theme, and I want to add a single Views template to the theme.

Initially, I created a blank subtheme, but some of Corollas settings don't show up on my subtheme's settings page, so apparently this changed functionality.

Now I'm considering simply keeping my template as a local patch to Corolla as that's a way of solving the problem that I understand well.

How would you go about solving this issue?

# Answer
The theme settings not being inherited by the subtheme is a Drupal core bug. If you simply copy the theme settings from the parent's .info file to the subtheme's .info file, it will alleviate the issue.

However, keeping a local patch of the theme is a reasonable solution in this case. The rule of "dont edit a contrib theme" is really in place just to ease potential updates, etc. for users who may be unaware of the risk of losing their changes upon updating themes/modules.
> 4 votes

# Answer
If the only thing you are changing is one of a module's theme templates, and nothing with respect to the theme itself, I'd just create a subdirectory in the theme named after the module and stuff the template in there. So, in this case it would be `.../sites/all/themes/corolla/views/views-____.tpl.php` If you start doing this with a lot of modules' templates, you might consider creating a template directory itself and then module-name subdirectories, eg, `...sites/all/themes/corolla/tpl/views` but this is just personal neatness preferences now. Either way, the theme system will recurse down through its directory looking for the templates (eg they don't need to be in the theme's root directory cluttering things up)
> 0 votes

---
Tags: theming
---


# Question
Title: Creating separate list of a custom content type for every user
I have a custom content type named Movie.

Every user must have 2 lists of movies :-

1) Seen Movies

2) Unseen Movies

For this purpose a ADD button (or 2 buttons - 1. add to seen, and 2. add to unseen) should appear on every movie page , by which a user can add the corresponding movie to his seen list or unseen list.

How can i do this??

I am using Drupal 7.

I am new to drupal, so what should be my approach to solve this problem ?? Please help :-)

THANX IN ADVANCE

# Answer
> 0 votes
I would take a look a the flag module. It allows you to create an unlimited number of "flags" that can be placed on nodes that users can select/deselect. You could create one for "seen" and "unseen".

It has views support so you can create a view using the user id as an argument on each user's page that will show them which movies that have flagged.

---
Tags: 7, users, nodes
---


title: Contextual filter with a block view

text:
# Question
Title: Contextual filter with a block view
I have a page view("/news") with contextual filter for the topics ("news/design","news/coding"...) which are taxonomy terms and this worked fine. Due to some changes for the mobile theming, I need a block view instead of the page view, but I can't get it to work with the filters.

With the old filter settings I get all my articles in "/news", but the filter I am using changed the default value from the filter to "taxonomy term ID from url"; I now see an empty page for "/news" (this is now a simple page with the block view included) and a "site not found" for "/news/design" etc. In the preview of the view, everything works fine.

These are the settings for the view.

# Answer
In general, the reason this block isn't working is that a block does not have an assigned path and the contextual filter does not have a path to work on. To connect the block to a path return to the contextual filter settings and in the section `What to do if the URL is not available` select `Provide default value` and select `Raw value from URL` from the dropdown box. From the `Path Component` box select the position in the URL that your contextual filter gets its value.

In your specific case you have told the view to interpret the URL as a taxonomy term and that is probably not the format of your URL (taxonomy/term/tid). The Views UI is a bit misleading in that it suggests that the alias can be used in the contextual filter when it does not. Drupal converts the alias to the base URL value when it calls the view and that is what is directly available in the contextual filter. To use the alias you must specifically inform it as described above. Views is powerful, but a bit tricky to use. One tool you can use if you have some experience with SQL queries, is to turn on the display of the queries in the View preview display in the Settings tab. This will tell you what views is trying to do when the view is called.

More can be found on this issue at this question
> 35 votes

---
Tags: blocks, views
---


# Question
Title: Content type title field not available in manage display
I have two customized content types, both having a title field. Yet this field does not appear in the Manage Display panel. Moreover, they are not displayed when the content is displayed.

Is this normal? How can I access those title fields? How can I have them displayed?

# Answer
> 1 votes
It is not normal but may be the theme you use does not display page title or you hide it with css anyway you can go to node.tpl and write echo $node-\>title to check that

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


title: Override quicktabs tab titles

text:
# Question
Title: Override quicktabs tab titles
I have a quicktabs instance that shows lists of content by year (2012, 2011, 2010 and so on). Each tab is a views generated block that pulls content by date using relative values (current year, current year-1, etc.). How can I override the title of each of the tabs so that I don´t have to hardcode year values as tabs titles? Thanks in advance.

# Answer
I finally got this to work by adding on my template.php:

```
function YOURTHEME_quicktabs_alter($quicktabs) {
if ($quicktabs->machine_name == 'YOUR_QTABS_NAME') {
  $currYear = date('Y');
  for ($i = 0; $i <= 3 ; $i++ ) {
    $yr = ($currYear-$i);
    $quicktabs->tabs[$i]['title'] = t($yr);
  }
}

```

} }
> 3 votes

---
Tags: blocks
---


# Question
Title: How to print a table create with views, using a submit button below the view?
I created a custom template for my views (table) and I inserted a button below the table.

By clicking on that button I would like the table to be shown in a new page, from which that table can be printed.

Or to say it in another way: I want to embed to new page via such button.

How can I do this?

# Answer
> 0 votes
If I am interpreting this correctly, you want to click on a link and then have a page painted on your screen with JUST the view in it, no other blocks of information, just a clean display of the view information so the user can right click (or what have you) and then print this page and have it printed out without all that extra "stuff" on the page.

If that is correct, what you would need to do is:

1. Have a link created in your table that links to another page, let's call it `print/thisview`.
2. In the Views UI, create a duplicate page display that calls the view in question with `print/thisview` as the path.
3. In your theme, create a `page-print-thisview.tpl.php` template that contains only the content region, none of the other regions.
4. Clear all caches.

Now, if all is correct in the world, meaning I have oversimplified this a great deal, when you click on that link, it will paint the screen in a clean format that is nice for printing.

---
Tags: 7, views
---


title: views filter's identifier

text:
# Question
Title: views filter's identifier
I'm using drupal 7.

I want to use `$view->set_exposed_input(array('filter_identifier' => 'filter_value'));`

How to know the filter identifier?

# Answer
> 2 votes
When you create the view exposed filter you can give it a name. You use the default name it gives you, or whatever you choose it to be. See attached image.

---
Tags: 7, views
---


# Question
Title: 500 error: Output filter: Response body too large
I recently copied a drupal 7 site from my development server to my production server. Everything on the site seems to be working as expected, except for when I log in as the admin user and try to access `admin/modules`. When I go there I get a 500 "Internal Server Error" page. In the server's error log, I get: `ModSecurity: Output filter: Response body too large (over limit of 6291456, total not specified). [hostname "(my hostname)"] [uri "/drupal/index.php"] [unique_id "T4JOln8AAAEAAFLlyE4AAAAK"]`

(`unique_id` changes every time I get the error, but the other parts don't.)

Any idea what could be causing this?

# Answer
It turns out that I needed to disable the devel module. I don't know exactly what was causing the problem -- devel certainly doesn't write 6M of debugging information to the page locally.

Disabling the module was nontrivial since the problem was preventing the modules page from loading. I needed to disable devel on my development server, then sync the database on the production server with it.

Thanks to the folks on #drupal who helped me solve this.
> 1 votes

# Answer
ModSecurity is an Apache module (a Web Application Firewall) that protects sites from i.e SQL injectiosn, XSS attacks, prevents php shell execution and so on. You must contact your hoster and let them know because they need to change modsec rules maybe.
> 4 votes

---
Tags: wsod
---


# Question
Title: Drupal local configuration clone. Only home page is accessible
I have cloned an existing drupal installation, the problem is, I can see only the home page, other url's are not working.My apache rewrite module is configured. I can not log in as any kind of user.

# Answer
I did face with a similar problem when moving my site from local machine to dev server. but here is what i did

1. Install Backup and Migrate to download the existing database and Backup and Migrate Files to your local drupal installation.
2. Go to http://local-site/admin/config/system/backup\_migrate and then backup the default database and local files to download

3. Install fresh copy of drupal with new database at the server(or to the location where you are cloning.
4. Copy from http://local-site/sites/all/modules and http://local-site/sites/all/themes to their respective directories at the server(or your cloning destination)
5. Enable both the modules in step 1, from http://local-site/admin/modules
6. Go to http://cloned-site/admin/config/system/backup\_migrate/restore and restore the database and local files by browsing for the exported data at step 2

*and don't forget to enable the theme which you used on the local-site before using backup and migrate.*
> 1 votes

# Answer
Maybe you missed to update the `$base_url` from sites/default/settings.php to your new sites url. For multi-site installation please enter the appropriate url(e.g. http://clone-location/site1)
> 1 votes

---
Tags: uri, users
---


# Question
Title: How to change the path of views content?
have developed a website for my team and used VIEWS for all the link in the website.

While trying to click the links from client system it shows some error that says remote connection doesn't accept it.. like localhost some problem.. i don know how to resolve it..

I use to paste the IP address of the server and open in client system, so while doing like that in client system it will show this **"http://localhost:8082/"** . So i think the client system takes the local host so can anybody have an idea to resolve it.

The remote device or resource won't accept the connection. after troublshooting the result is this.

# Answer
may be you have used absolute url(starting from *http://localhost:8082/content/..*) instead of relative url(starting directly from *content/..*)
> 1 votes

---
Tags: entities, views
---


title: Drupal Database Join

text:
# Question
Title: Drupal Database Join
I am creating a content type in Drupal - a content management system for our business rules. This content type will ultimately contain about 40 fields. I notice that for each field I create for the content, Drupal creates a table in MySQL.

It sounds like when I go to query the content in MySQL from a remote system using, say, JDBC, will I need to create a query joining 40 or so tables?

Does that sound right? Can I be doing something wrong? I cannot believe that a query, even with adequate indexes in place, would be performant when 40 tables are joined together.

# Answer
40 fields on a single content type sounds a lot to me, although I'm aware of sites with a great deal more.

1. The very first thing you probably want to to, is use Entity Cache which should significantly reduce the query complexity for you, though honestly I haven't examined the module in detail.
2. Aggresively cache higher up the chain as well. Varnish, Page manager and Cache actions are all your friends here.
3. Is it possible for you to meaningfully break down the content type into pieces? If you can identify parts of the content type that will not always be necessary, use a Relation to a second content type. At the price of two optional extra joins, you can potentially skip a lot of them.
4. Still no luck? Define your own content type where all your data columns are **properties** instead of **fields**. This will store all data in the same table, at the cost of flexibility. It's probably also possible to make field api do the same thing with fields, but I have never even considered how to do that.
> 2 votes

---
Tags: views, database
---


# Question
Title: Form not showing in administration menu in Drupal6
I'm trying to create a simple form with a textfield in the administration panel but I get the message "You do not have any administrative items"

Here is the code inside my ptm\_autocomplete.module:

```
function ptm_autocomplete_menu() {
  $items['admin/prestum/autocomplete'] = array(
    'title' => 'Autocomplete',
    'description' => 'Autocomplete',
    'page_callback' => 'drupal_get_form',
    'page arguments' => array('ptm_autocomplete_form', array(), array()),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

function ptm_autocomplete_form(&$form_state, $unused, $form_values) {
  $form = array();

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Color'),
    '#description' => t('Color'),
  );

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

  return $form;
}

```

Any ideas what might be wrong?

# Answer
You have an an underscore (`_`) in `page_callback`. Remove that, clear the caches, and you should be good to go.

```
function ptm_autocomplete_menu() {
  $items['admin/prestum/autocomplete'] = array(
    'title' => 'Autocomplete',
    'description' => 'Autocomplete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ptm_autocomplete_form', array(), array()),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

```

Also if this is Drupal 7 your form function should have `$form` as the first param:

```
function ptm_autocomplete_form($form, &$form_state, $unused, $form_values) { ...

```

But not for Drupal 6.
> 2 votes

---
Tags: routes, forms
---


# Question
Title: Connecting Commerce module with registered users
I have a site that forces users to register before they can make any purchase, But I can't figure out a way to get the information from the registered users on my site and use it in my commerce module customer profile, so people don't have to enter their information again while making a purchase.

Using: Drupal 7 Commerce Module

# Answer
Commerce Addressbook could be useful for you.
> 1 votes

# Answer
Another option is Commerce Extra

> **Feature/improvement overview**
>
> * Improve checkout by pre-populating customer profile information's addressfield. Needs an address field for user entity. See also
> Commerce Addressbook for similiar functionality.
> * Add extra step where user may login, but doesn't require it.
> * Improve quantity field by wrapping it with decrease/increase button links.
> 0 votes

---
Tags: 7, commerce
---


title: Override a content page in drupal 7

text:
# Question
Title: Override a content page in drupal 7
There is any way to override the content page of a particular content type in drupal 7.

By default the content page has the sidebar on the right hand side and the content is placed on the left side

```
 Page design:

 Content- width 650px | Left sidebar 500px

```

Here if the content type is company\_profile then the width of the content type should be 1050px and the side bar should be below the content page with width 500px as show in the below image

Can anyone help me how to override the content page when the content type is company\_profile

# Answer
> 3 votes
You can either use hook\_preprocess\_node() and if the content type is company\_profile, change the styling. Or you can have a node--company\_profile.tpl.php file and render that particular content type the way you want.

Then you can use CSS to do get things done. If you use a grid based layout such as 960.gs, this would be easier.

# Answer
> 2 votes
Have a look at Overriding Page Templates per Content Type in Drupal 7 for a full overview, but basically you need to implement this in your theme's template.php file:

```
function yourthemename_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```

Then you'll be able to create content type specific page template files like `page--article.tpl.php` and `page--page.tpl.php`...or for your particular case, `page--company_profile.tpl.php`.

Remember to clear Drupal's cache after you do either of the above, otherwise the theme registry won't be updated with your changes.

# Answer
> 0 votes
This you shall do entirely from your theme file (yourtheme.info) by redefining the region names; The rest is css float job and #region-name width setting.

For a particular content-type use this pattern: node--CONTENT-TYPE.tpl.php e.g. node--company\_profile.tpl.php

where you copy the node.tpl.php content and edit according to you own wish.

---
Tags: nodes
---


# Question
Title: Using Memcache Effectively with Drupal 7 Multisite
I am setting a hit ratio of 55% on our memcache instance (v1.4.4) and am wondering what can be done to improve the hit ratio. We're in a multisite setup (30+ sites), with two load balanced web servers; there is an instance of memcached on each web server.

In the `settings.php`, I have:

```
$conf['memcache_servers'] = array(
         '11.22.33.44:11211' => 'default',
         '11.22.33.45:11211' => 'default',
      );
$conf['memcache_bins'] = array('cache' => 'default');
$conf['memcache_key_prefix'] = $_SERVER['SERVER_NAME'];

```

I am looking at using bins to improve hit ratio, but have come across some suggestions that the latest memcache module does this already, but I am unsure as the instructions with the module contain directions on setting up bins.

If bins are they way to go, how do you determine what (table?) needs to have its own bin? These are the cache tables that I have in my sites:

```
cache
cache_admin_menu (empty)
cache_block (empty)
cache_bootstrap
cache_field
cache_filter (empty)
cache_form (empty)
cache_image (empty)
cache_media_xml (empty)
cache_menu
cache_page (empty)
cache_path (empty)
cache_token (empty)
cache_update (empty)
cache_views
cache_views_data (empty)
ctools_css_cache (empty)
ctools_object_cache (empty)

```

In addition to bins, what else can I be doing to improve memcached usage?

Many thanks!

# Answer
After much research, here is what has helped our hit ratio and memcached usage:

* Upgraded memcached to 1.4.10 (the latest version with performance improvements)
* Enabled binary format and compression
* Use the default for bins

Our memcached conf in settings.php looks something like this now:

```
$conf['memcache_bins'] = array('cache' => 'default');
$conf['memcache_options'] = array(
  Memcached::OPT_COMPRESSION => TRUE,
  Memcached::OPT_BINARY_PROTOCOL => TRUE,
  );
$conf['memcache_persistent'] = TRUE;
$conf['memcache_key_prefix'] = $_SERVER['SERVER_NAME'];

```

**Biggest Gains**

The biggest gain for us was enabling compression, even though the documentations states that it increases CPU cycles. We have 4 CPUs allocated to our VM, and have not noticed a difference. Time for memcached calls went from ~1250ms to ~150ms (obtained from NewRelic) for creating a piece of content (custom Article in our case).

**Hit Ratio**

Our hit ratio is now ~70% -- much better than 55% earlier, but not quiet the 90%+ that some have reported ... the quest continues (-:

Hopefully this helps someone else. If you come across other improvements or have corrections/suggestions, please post comments or answers.

**Update -- Version of memcahe module**

We went from version 1.0-beta4 to 1.0 and our hit ratio now is 87% . I had to restart memcached as hit ratio wasn't going past 70%. We have 64MB allocated to memcached at the moment, so this was not a big deal for us.
> 13 votes

---
Tags: caching, performance
---


# Question
Title: user/%/edit - remove it from tab and make it an actual menu item
I am pretty clueless on how drupal handles such things and I can't seem to grasp the context.

I want a menu link to user/%/edit (using menu token already). But as it seems /edit is a 'tab' item of the user/% menu (also saw it in the db). Using theming I have visually removed the unwanted tabs and I've also merged the user/edit form with the profile2 forms I need for extra fields using form\_alter.

The problem is that even though I have a menu link called "My Account" linking to user/%/edit, whenever I click it to go there, the "Edit" menu link appears as active in my main menu instead of the "My Account".

Is there any way to remedy this?

If the question is not clear I will revise it cause it's a pretty confusing issue.

EDIT: to avoid similar answers, the problem is not how to visually remove the tabs, the problem is how to somehow alter or ignore the user/\* menu structure so the "Edit" part is not a separate tab anymore and thus it won't show when I click the link that leads to to user/%/edit

# Answer
> 0 votes
Ok guys figured it out. The 'bug' part was cause I was using Menu Position for various reasons including this portion of the sub-menu and it had a settings tab that I didn't notice before.

Switching from "Insert the current page's title into the menu tree" - which caused the "Edit" to get inserted - to "Mark the rule's parent menu item as being "active"" fixed it all for me.

Other than that I just had to use menu token as usual to create the actual url to the edit page. But all the fuss was because of that one wrong setting, thanks for your time.

# Answer
> 3 votes
You want to alter the original menu item that was defined in user.module's `hook_menu()`. You can do this in hook\_menu\_alter().

The item's array key is simply the path, so:

```
function hook_menu_alter(&$items) {
  $items['user/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'my_custom_page_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
  ),
}

```

# Answer
> 3 votes
Those that will stumble upon this looking for a way to do this without coding and using existing modules try using:

1. The Tab Tamer module to remove the account 'edit' tab. It is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
2. The Menu Token module to move the account edit menu item to any other menu. This module provides tokens, that could be used in title or in path of menu items (links). For example, if you create menu item with path: "user/\[current-user:uid\]/edit", the url will be changed "on fly" to: "user/1/edit" (assuming you are user 1).

# Answer
> 0 votes
If I understand correctly, you might be able to utilise `menu_tree_set_path()` in a custom module.

EDIT:

It look like the Menu Trail By Path module might do what you want to long as the path is correct! It utilises `menu_tree_set_path()` and takes all the legwork out for you!

---
Tags: 7, routes
---


# Question
Title: How to correctly install PHPMailer + Messaging on Drupal 6
I have a Drupal 6 site where I would like to use PHPMailer to send notifications about newly created nodes and such. When I install PHPMailer 6.x-3.1, it needs Libraries and that phpmailer be placed under sites/libraries. As I want different notifications for each content type, I installed Notifications 6.x-4.0-beta7 and Messaging 6.x-4.0-beta8. What confuses me, is that I have two different places where PHPMailer can be configured, and they can have different settings: http://mysite.com/admin/messaging/settings/method/phpmailer and http://mysite.com/admin/settings/phpmailer. Can anyone confirm my setup?

BTW: I had some trouble finding out that existing subscriptions had to be replaced with new (or edited in database) to move from notifications to notifications\_content. Might be a help for others.

# Answer
I have chosen to not use the messaging\_phpmailer module and only rely on the PHPMailer module. It works now, but notification/messaging is a mess on Drupal (at least with the beta-versions I'm running). Users email addresses are copied from table users to table notifications(.destination) and table messaging\_destination(.address), and sometimes it is not. Maybe it happened during update, but I had to manually update the two via SQL updates, before notification works,. Until I did, the log was filling up with PHPMailer errors 'Invalid Address'. What's worse, when a user changes his e-mail, the subscriptions copies are not updated, so notifications are still send to the first email address. You have to tell your users to unsubscribe before changing email, and then subscribe again...

Kind regards The Roadrunner
> 1 votes

---
Tags: emails, notifications
---


title: Views image not visible?

text:
# Question
Title: Views image not visible?
I'm using the Drupal Commerce module, and there is no "Latest products" block.
I am trying to make a "Latest Products" view, but the images of the products are not visible in the view; however, the titles are OK.

Here is the field that I choose for the product.

What am I missing? I suspect of the permissions but I could not find any Permission except these two.

---

This is the exported code of the view I am using.

```
$view = new view;
$view->name = 'latest_products';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Latest products';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Latest products';
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '2';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: Field: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['external'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['field_image']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['field_image']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['trim'] = 0;
$handler->display->display_options['fields']['field_image']['alter']['html'] = 0;
$handler->display->display_options['fields']['field_image']['element_label_colon'] = 1;
$handler->display->display_options['fields']['field_image']['element_default_classes'] = 1;
$handler->display->display_options['fields']['field_image']['hide_empty'] = 0;
$handler->display->display_options['fields']['field_image']['empty_zero'] = 0;
$handler->display->display_options['fields']['field_image']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_image']['field_api_classes'] = 0;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Latest Products Block */
$handler = $view->new_display('block', 'Latest Products Block', 'block');
$handler->display->display_options['block_description'] = 'Latest products Block';

```

I looked at the source of the page but the image is not rendered.

---

My problem is with the content type. There are 2 types: *Product display*, and *Product*.

When I look at the content types, the actual "Product" is not there.

The actual images are stored in the Entity "Product" which is referenced here as "Product Reference" thats why I cant see the images in my view.

I tried with a dummy content type(including images) without problems I see the images in my view.

Now my question is; How can I choose the images from the Entity Product while listing the "Product Display" type in my view?

These are the screenshots while creating the view.

When I add the fields, the image seems empty.

# Answer
> 3 votes
I found the answer, it was the **relationships**
I needed to use Relationship in order to select images of Product(not of Product Display)

Then select the relation while choosing the image field

# Answer
> 1 votes
Make sure the public directory for image uploading is writable, dblog will tell you if there is a problem with that.

# Answer
> 0 votes
Try going through the HTML to see whether a path to the image is printed out.

You can copy-paste the HTML in a text file and attach it here for us to see. Also, export your view and attach that also to your post.

---
Tags: views, media
---


# Question
Title: drupal module secure pages toggles between http and https on reload
I am using the secure pages drupal module to enable https for some of the pages , but i have noticed one bug in this , each time i reload the page its toggling between http and https, and if i go from a secure page to another secure page(ex: login to registration which are bith secure according to settings) the destination page will be in http but if i refresh it toggles between secure and non secure , a similar issue is reported here

# Answer
The source of the problem could be in several places, depending on which webserver you're using, how it's configured, etc.

Are you using Apache with mod\_ssl? NOthing else 'in front', like nginx doing the SSL handshaking instead?

In any case, I'm guessing that your webserver's not consistenly serving up the required server var. In 'securepages.module', there's a check for

```
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? TRUE : FALSE;

```

Not knowing your webserver config, find out what your webserver is doing. add,

```
<?php
 phpinfo();
?>

```

to your pages and look to see what the values of

```
$_SERVER['HTTPS']
$_SERVER[SERVER_PORT]

```

are. Or simply print them out directly ... Check if/how those values toggle on page refresh.

I'm suspicious of caching, too.
> 2 votes

# Answer
To ensure that they donot toggle between http and https, go to secure pages and let say you want to make a specific link 'mylink' secure. Write (use aesterik and forward slash before link and (forward slash and aesterik) after your link) in the list of secured pages to ensure that it is secured. I did it in multilingual site and it worked for me.

Posted this thing so that any one can take advantage of it. :)
> 1 votes

---
Tags: 7, security
---


# Question
Title: Severe health issues are found on your site
I have just put a Drupal website online. I registered it in Google WebMaster's tool and it sent me back a `Severe health issues are found on your site` message related to a `robot.txt` file.

The content of this file is:

```
#
# robots.txt
#
# This file is to prevent the crawling and indexing of certain parts
# of your site by web crawlers and spiders run by sites like Yahoo!
# and Google. By telling these "robots" where not to go on your site,
# you save bandwidth and server resources.
#
# This file will be ignored unless it is at the root of your host:
# Used:    http://example.com/robots.txt
# Ignored: http://example.com/site/robots.txt
#
# For more information about the robots.txt standard, see:
# http://www.robotstxt.org/wc/robots.html
#
# For syntax checking, see:
# http://www.sxw.org.uk/computing/robots/check.html

User-agent: *
Crawl-delay: 10
# Directories
Disallow: /includes/
Disallow: /misc/
Disallow: /modules/
Disallow: /profiles/
Disallow: /scripts/
Disallow: /themes/
# Files
Disallow: /CHANGELOG.txt
Disallow: /cron.php
Disallow: /INSTALL.mysql.txt
Disallow: /INSTALL.pgsql.txt
Disallow: /INSTALL.sqlite.txt
Disallow: /install.php
Disallow: /INSTALL.txt
Disallow: /LICENSE.txt
Disallow: /MAINTAINERS.txt
Disallow: /update.php
Disallow: /UPGRADE.txt
Disallow: /xmlrpc.php
# Paths (clean URLs)
Disallow: /admin/
Disallow: /comment/reply/
Disallow: /filter/tips/
Disallow: /node/add/
Disallow: /search/
Disallow: /user/register/
Disallow: /user/password/
Disallow: /user/login/
Disallow: /user/logout/
# Paths (no clean URLs)
Disallow: /?q=admin/
Disallow: /?q=comment/reply/
Disallow: /?q=filter/tips/
Disallow: /?q=node/add/
Disallow: /?q=search/
Disallow: /?q=user/password/
Disallow: /?q=user/register/
Disallow: /?q=user/login/
Disallow: /?q=user/logout/

```

I believe Drupal generated this itself.

I have another Drupal site live, but it does not have a `robot.txt` file, and Google WebMaster Tool does not throw me such messages.

How to solve this issue? Is it safe to remove my `robot.txt` file?

**UPDATE**

I am still struggling with these strange warning messages from Google Webmaster Tools on my Drupal website:

```
Is robots.txt blocking important pages?
Some important page is blocked by robots.txt.

```

When I click on 'important page', it points to:

```
http://www.mydrupalsite.com/misc/jquery.js?v=1.4.4

```

Why would Google want to access `/misc`?

# Answer
There's nothing in your robots.txt file that is out of the ordinary and for the most part you probably want to keep all of those exclusions, checks, etc. to save on bandwidth and for security. The health message you're seeing is likely due to another issue within the site or maybe just a temporary Google hiccup that will resolve itself shortly. Are there any other messages within the Google Webmasters page that indicate other issues, ex. permission problems?

Another possibility is to submit an XML Sitemap to Google directly to tell it exactly what you are expecting it to index:

http://drupal.org/project/xmlsitemap

I've found that this resolves some Google crawl issues in the past.
> 4 votes

---
Tags: 7
---


title: correct the url context

text:
# Question
Title: correct the url context
When using $link = $\_SERVER\['QUERY\_STRING'\]; in page.tpl.php the result of print is:
`f1=All&f2%5Bvalue%5D%5Byear%5D=2009&f2%5Bvalue%5D%5Bmonth%5D=1`
Is there a way to correct the url to print as:
`f1=All&f2[value][year]=2009&f2[value][month]=1` Thanks.

# Answer
> 3 votes
You just need to decode the string with `urldecode()`:

```
$query_string = urldecode($_SERVER['QUERY_STRING']);

```

---
Tags: 7, uri
---


title: can't get values from url

text:
# Question
Title: can't get values from url
i sent values with url `http://localhost/mysite/pagename?f1=1&f2[value][year]=2009&f2[value][month]=1` (i'm sending filters values) in the directed page i'm trying to get this value by $\_GET\[\] but when i print it nothing show up(i thinks it's null).
here is my code:

```
<?php
$f1= $_GET['f1'];
$year = $_GET['f2']['value']['year'];
$month = $_GET['f2']['value']['month'];
drupal_set_message($f1,true);
drupal_set_message($month,true);
drupal_set_message($month,true);
$view = views_get_view('emp1')
$view->set_exposed_input(array('f1' => $f1,'f2' => array('year' => $year, 'month' =>   $month)),);
$display_id = 'default';
$view->set_display($display_id);
$view->render();
print($view->preview());
?>

```

# Answer
> 1 votes
You should be able to get your values like this:

```
$year = $_GET['f2']['value']['year'];
$month = $_GET['f2']['value']['month'];

```

---
Tags: 7, uri
---


# Question
Title: Where does redirect from default search to apachesolr_search occur?
We're using the apachesolr\_search module on our site. (This is a site I inherited fully coded, so there's tons going on that I'm not intimately familiar with yet.) We have a search block that has been customized (see this post for details; we did eventually get the radio buttons to display, although in a really dirty, non-drupal way.)

I'm trying to get the form values on submit. Forgetting for a moment the radio buttons, I can't even figure out a way to get the value of the search box. Obviously it's getting passed to the solr search, but when I look at the Net panel in Firebug, there are no POST requests, only GET. In my submit function (which does run), I've tried `print_r('$_POST')`, `echo $form_state['values']['search_box']` (where search\_box is the element name of the actual form element), tried looping through `$form_state` and printing all key/value pairs... nothing. Not a single one of these returns anything.

Obviously there's a redirect occurring somewhere that sends the value of the search\_box to the solr search module to build the GET request, but I can't for the life of me figure out where it's happening. I think in order to see the values of the posted form, I'd need to intercept the values before the redirect - how do I do that?

# Answer
> 0 votes
Unless I'm mistaken, there is no redirect taking place. Instead the `hook_search` is used, which will pass the search params from the url.

# Answer
> 0 votes
The redirect happens in `search_form_submit()` with this line:

```
$form_state['redirect'] = 'search/' . $type . '/' . $keys;

```

You can override it in a `hook_form_alter()` like so:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_box_form' || $form_id == 'search_block_form' || $form_id == 'search_theme_form') {
    // Alter the form if you need to
    $form['something']['#some-attribute'] = 'something';

    // Add a submit handler if you want to alter the redirect
    $form['#submit'][] = 'MYMODULE_search_form_submit';
  }
}

function MYMODULE_search_form_submit(&$form, &$form_state) {
    // Redirect to somewhere else if that's what you're after
    $form_state['redirect'] = 'somewhere-else';
  }
}

```

---
Tags: 6, search
---


title: I'm missing my core search module

text:
# Question
Title: I'm missing my core search module
I'm running Drupal 7.12 and had to build a module that extends the search functions of the core Search Module. I made the module, installed it in my custom module folder and reloaded my Drupal site only to find that the search bar couldn't be found on the page...

I looked through the module selector on my dashboard and looked through the core modules. Surprisingly, there was no search module listed in the core module section, although my module did show up in my custom module section (which is irrelevant because the module I wrote needs the core search engine to work).

I checked through my Drupal on my FTP site and found that the files for the core search module are still there.

Why isn't it appearing in my dashboard core module list, and how do I get my Drupal site to recognize that the files are still there?

# Answer
> 3 votes
I'd guess that your custom module is called `search`, which would conflict with the core Search module, also named `search`.

There's no such thing as namespaces with regards to Drupal modules (at least out of the box, I'm not sure if there are any contrib modules that deal with this. My gut instinct is that there wouldn't be). Each module needs to be individually named, or the last module of the same name that Drupal comes across will be the one it uses.

Make sure your module is not called `search`; that includes making sure the folder name for the module, the name of the `.info` file, name of `.module` file, etc. are not called `search.info` etc. That should make sure that both modules are available in your module list.

---
Tags: 7, search
---


title: Setting up form table checkboxes

text:
# Question
Title: Setting up form table checkboxes
I'm trying to create a form table with a column of checkboxes. The theming isn't working with the code below. All help is appreciated :)

**myadmin.module**

```
function myadmin_menu() {

  $weight=0;

  $t = get_t();

  $items = array();

  $items['myadmin_dispute'] = array(
    'title' => 'Dispute Queue',
    'access arguments' => array('view myadmin'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myadmin_dispute'),
    'file' => 'myadmin_dispute.php',
    'type' => MENU_NORMAL_ITEM,
    'expanded' => true,
    'weight' => $weight++,
    'menu_name' => 'myadmin',
    'module' => 'myadmin',
  );
}

```

**myadmin\_dispute.php**

```
function myadmin_dispute($form_state) {
    //add output - css and javascript to include
    drupal_add_js ( drupal_get_path ( 'module', 'myadmin' ) . '/scripts/jquery.tablesorter.js' );
    drupal_add_js ( drupal_get_path ( 'module', 'myadmin' ) . '/scripts/myadmin.js' );
    drupal_add_css ( drupal_get_path ( 'module', 'myadmin' ) . '/blue/style.css' );

    $disputes = array
      (
        array('uid' => 1, 'first' => 'Joe', 'last' => 'Smith'),
        array('uid' => 2, 'first' => 'Susan', 'last' => 'Doe'),
        array('uid' => 3, 'first' => 'John', 'last' => 'Doe'),
      );

    foreach($disputes as $dispute)
      {
        $checkboxes[$dispute['uid']] = '';
        $form[$dispute['uid']]['first_name'] = array
        (
          '#value' => $dispute['first'],
        );
        $form[$dispute['uid']]['last_name'] = array
        (
          '#value' => $dispute['last'],
        );
      }

    $form['checkboxes'] = array
      (
        '#type' => 'checkboxes',
        '#options' => $checkboxes,
      );
      $form['#theme'] = 'dispute_theme';

      return $form;

}

function myadmin_dispute_theme()
{
  return array
  (
    'dispute_theme' => array
    (
      'arguments' => array('form' => NULL),
    ),
  );
}

function theme_dispute_theme($form)
{
  $rows = array();
  foreach(element_children($form['checkboxes']) as $uid)
  {
    $row = array();
    $row[] = drupal_render($form['checkboxes'][$uid]);
    $row[] = drupal_render($form[$uid]['first_name']);
    $row[] = drupal_render($form[$uid]['last_name']);
    $rows[] = $row;
  }

  if(count($rows))
  {
    $header = array(theme('table_select_header_cell') , t('First Name'), t('Last Name'));
  }
  else
  {
    $header = array(t('First Name'), t('Last Name'));
    $row = array();
    $row[] = array
    (
      'data' => t('No users were found'),
      'colspan' => 2,
      'style' => 'text-align:center',
    );
    $rows[] = $row;
  }

  $output = theme('table', $header, $rows);
  return $output . drupal_render($form);
}

function myadmin_dispute_submit($form_id, &$form_state) {

}

```

---

Update, this is needs to work for drupal 6 instance.

# Answer
Drupal has a built-in tableselect element type for situations just like this, it would be a lot easier to use that instead:

```
$disputes = array(
  1 => array('Joe', 'Smith'),
  2 => array('Susan', 'Doe'),
  3 => array('John', 'Doe')
);

$header = array(t('First Name'), t('Last Name'));

$form['checkboxes'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $disputes,
  '#empty' => 'No users were found.'
);

```

The above code produces this table:

In your form submit function you can get the selected user ids with code like this:

```
$selected_uids = array_filter($form_state['values']['checkboxes']);

```

**EDIT**

The above is for Drupal 7, if you're using Drupal 6 you can use the same code but you need to install the Elements module.
> 4 votes

---
Tags: theming, forms, 6
---


# Question
Title: Where to collect business logic for Entity models?
Thinking of entities as an MVC 'Model', where would the business logic for an entity sit? I have a custom EntityController, but that isn't attached to an instance and seems to be intended only for *serialization* logic. I need a Model class that has the same properties as the entity StdClass, but also has functions for operating on the data and presenting it.

I am currently wrapping the entity with a real Model class that is created by its static function Model::createFromEntity($entity)

# Answer
> 2 votes
You can use the Entity API which allows to specify the class in hook\_entity\_info(). Then entity\_load() will use that class (assuming that you're using/extending from EntityAPIController, not the core one) then it will return instances of the defined class and not dumb stdClass objects. Then you can define your own methods there.

See http://www.trellon.com/content/blog/creating-own-entities-entity-api for an example.

This feature will be in Drupal 8 (already is and core is currently being ported to it).

---
Tags: entities
---


# Question
Title: How to display translated term names in exposed form in block
So I've got a views page displaying a list of nodes from specific content type. This view has filter form exposed in a block.

Some of the filters in the form are vocabularies. I'm using the BEF module to display the terms from each vocabulary as checkboxes instead of the default select lists.

The terms are translated - I'm using **i18ntaxonomy** for that, the vocabularies have this option selected: *Localize terms. Terms are common for all languages, but their name and description may be localized.*

The problem is that when the site is displayed in other languages different than the default one, the terms in the form are not translated.

I guess the problem is not with BEF as when I disable the module the terms remain untranslated.

I'm looking for any advice on how to debug/solve this issue.

This is definitely not the correct way to do it, but as the project deadline is tomorrow I've got no other choice but to hack the views module source code:

```
--- a/htdocs/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc
+++ b/htdocs/sites/all/modules/views/modules/taxonomy/views_handler_filter_term_node_tid.inc
@@ -122,7 +122,7 @@ class views_handler_filter_term_node_tid extends views_handler_filter_many_to_on
           $result = db_query("SELECT td.* FROM {term_data} td INNER JOIN {vocabulary} v ON td.vid = v.vid ORDER BY v.weight, v.name, td.weight, td.name");
         }
         while ($term = db_fetch_object($result)) {
-          $options[$term->tid] = $term->name;
+          $options[$term->tid] = i18ntaxonomy_translate_term_name($term);
         }
       }

```

I don't think a patch for the views module will be accepted. Any suggestions how should I proceed with this?

# Answer
> 1 votes
Your best path would be to open an issue with Views after confirming that the terms don't translate correctly with BEF module disabled.

I found this issue related to translation in BEF's queue, but that looks to be slightly different or only part of your issue.

Unfortunately it can be difficult for contrib module maintainers to test their modules in multiple languages unless they happen to run their own multilingual site, so it is up to the community to make them aware of issues and help test patches.

You also might want to take a look at http://drupal.org/project/i18nviews

# Answer
> 1 votes
According to Martin, it's not an issue with BEF. I was struggling with this and after installing http://drupal.org/project/i18nviews I saw an option in my view that said: Profile: Country (field\_academy\_country) (translated) --\> In your case would be Content Type: Field title (field\_name) (translated). This provides me an exposed filter with translated terms. Hope this helps.

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