4

I created a select list box in the following format

Gender
1|Male
2|Female

I want to display the follwing information in a table but I am getting "1" for male and "2" for female.

Here is my code:

function display_results_submissions(){
$results = db_query("SELECT * FROM {users}");
$header = array( t('Name'), t('Mail'), t('Gender'),);

foreach($results as $result){
        $rows[] = array(

            $result->name,
            $result->mail,
            $result->gender,

            );
    }

    return theme('table', array('header' => $header, 'rows'=>$rows));
}

I want to display Male or Female instead of "1" and "2". How can I do so?

2 Answers 2

2

When saving the gender, the value that is stored in the database is the key and not the value. Hence, your database contained 1/2 instead of Male/Female. So, your query was right and only needed to format the key before storing in rows[].

function display_results_submissions(){
  $results = db_query("SELECT * FROM {users}");
  $header = array(t('Name'), t('Mail'), t('Gender'));
  foreach($results as $result){
    $gender = $result->gender == '1' ? t('Male') : t('Female');
    $rows[] = array(
      $result->name,
      $result->mail,
      $gender,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}
3

I think you should use entity_metadata_wrapper because when the select label changes you don't have to change your code.

Following lines will do what you want:

$wrapper = entity_metadata_wrapper('user', $result->uid);
$gender = $wrapper->field_user_gender->label();

So your code would look like:

function display_results_submissions(){
  $results = db_query("SELECT * FROM {users}");
  $header = array(t('Name'), t('Mail'), t('Gender'));
  foreach($results as $result){
    $wrapper = entity_metadata_wrapper('user', $result->uid);
    $gender = $wrapper->field_user_gender->label();
    $rows[] = array(
      $result->name,
      $result->mail,
      $gender,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}

There is a good blog post at http://www.mediacurrent.com/blog/entity-metadata-wrapper

2
  • Don't forget to replace "field_user_gender" with your field name :)
    – Irmela
    Jun 28, 2016 at 7:26
  • I liked you solution. I should start using entity metadata wrappers. Jun 28, 2016 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.