theme_table() isn't respecting sortable fieldname I generate some data in one of my modules and generate a table using theme_table(). I want the fields in that table to be sortable, but the table is being rendered with the wrong value in the links.

I'm getting ?sort=asc&amp;order=Birth Date instead of ?sort=asc&amp;order=field_birthdate.

Here is the code I'm using to generate my table:

$headerColumns = array(
    array('data'=&gt;'Name', 'field'=&gt;'title'),
    array('data'=&gt;'Edit'),
    array('data'=&gt;'Birth Date', 'field'=&gt;'field_birthdate'),
    array('data'=&gt;'Sex', 'field'=&gt;'field_sex'),
    array('data'=&gt;'Stars', 'field'=&gt;'field_stars')
);

return theme_table(array(
    'header' =&gt; $headerColumns,
    'rows' =&gt; $rows,
    'attributes' =&gt; array(),
    'caption' =&gt; '',
    'colgroups' =&gt; array(),
    'sticky' =&gt; true,
    'empty' =&gt; 'You ain\'t got none.',
));


I believe I'm generating that array according to the instructions on the theme_table() api docs, but it's not working.

How do I get the sort link url to properly use the fieldname I'm giving it in the render array?

EDIT: As requested, here is the code I use to generate my query:

$query = db_select('node', 'n')
            -&gt;fields('n', array('nid'))
            -&gt;condition('uid', $user-&gt;uid)
            -&gt;orderBy('type')
            ;

$direction = 'asc';
if (array_key_exists('sort', $_REQUEST) &amp;&amp; $_REQUEST['sort'] == 'desc') {
    $direction = 'desc';
}

if (array_key_exists('order', $_REQUEST) ) {
    $fieldname = strtolower($_REQUEST['order']);

    $field_info = field_info_field('field_'.$fieldname);
    if ($field_info !== null) {
        $table_name = _field_sql_storage_tablename($field_info);
        $query-&gt;innerJoin($table_name, 'f', 'f.entity_id = n.nid');

        $query-&gt;orderBy(sprintf('f.field_%s_value', $fieldname), $direction);
    }

}

$query-&gt;orderBy('title', 'asc');

if ($entityType !== null) {
    $query-&gt;condition('type', $entityType);
}

$records = $query-&gt;execute();
You're doing too much work.

For sorting:

$query = db_select('node', 'n')
        -&gt;fields('n', array('nid'))
        -&gt;condition('uid', $user-&gt;uid);

$sort_query = $query-&gt;extend("TableSort")-&gt;orderByHeader($headerColumns);
$records = $sort_query-&gt;execute();


Using the TableSort extension will simplify things immensely.