Как я могу назначить пользователям разные фотографии профиля при регистрации в зависимости от пола?


Моя настройка: Я нахожусь на Drupal 7, но не использую изображения профиля пользователя по умолчанию; вместо этого у меня есть настраиваемое поле изображения profile_picture, которое прикреплено к профилю пользователя. Когда пользователи регистрируются, они должны выбрать свой пол (Мужчина/Женщина/Предпочитают не говорить).

Я хотел бы назначить этому полю profile_picture другое изображение по умолчанию на основе значения, которое каждый пользователь выбирает для пола. Я попытался с помощью Установить значение данных с помощью правил, но я не могу понять узнайте, как сделать так, чтобы эти три конкретные фотографии (по одной для каждого выбора пола) были вариантами.

Если это поможет, у каждого пользователя также есть роль, основанная на их поле. Я не привержен использованию правил для этого; Я приму любое решение, которое позволит мне надежно установить изображение на основе значения поля в их профиле. У пользователей нет возможности изменить свой пол, поэтому его нужно установить только один раз.

ИЗМЕНИТЬ: Пользователи позже смогут заменить это своим собственным фотография профиля, поэтому мне нужно сохранить это как поле изображения.

Author: Patrick Kenny, 2012-07-19

5 answers

Простой подход может заключаться в том, чтобы переосмыслить само гендерное поле так, чтобы оно отображало изображение на основе его значения, например, вместо отображения male оно отображает изображение с путем sites/default/files/male.png.

В D6 это означало бы копирование content-field.tpl.php CCK в ваш каталог тем, а затем создание content-field-field_gender.tpl.php и изменение там, например...

print theme('image', 'sites/default/files/' . $item['view'] . '.png')

...вместо того, чтобы просто print $item['view'].

Мой быстрый взгляд на D7 здесь предполагает, что поле копирования field.tpl.php в field--gender--profile.tpl.php в вашей теме каталог был бы основной отправной точкой там и вместо того, чтобы отображать() в $item, делал бы что-то подобное с его значением.

Затем, в любой версии, просто убедитесь, что у вас есть три изображения в каталоге файлов под названием male.png, female.png и unknown.png (или файлы, основанные на любых значениях вашего гендерного поля.)

При таком подходе у вас есть только три файла для работы вместо файла, загруженного и сохраненного для каждого пользователя. Еще одно побочное преимущество заключается в том, что они будут легко кэшируется браузерами ваших пользователей.

ДОПОЛНЕНИЕ:

Основываясь на новой информации из комментариев и других ответов, вы могли бы сделать что-то подобное в своем шаблоне user-picture.tpl.php:

if (!empty($account->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($account->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
} else {

  $file_path = 'sites/default/files/' . $account->field_gender[LANGUAGE_NONE][0]['value'] . '.png';
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file_path));

}

Где новый материал - это else .... Простите мой D6ism, если sites/default/files неверен в D7, но в основном вам просто нужен путь в вашей системе к тому месту, где вы застряли male.png, female.png и unknown.png, и вы отображаете их, когда ваше поле profile_picture не задано.

 2
Author: Jimajamma, 2012-07-22 14:59:18

Один из способов - добавить пользовательский обработчик отправки для формы регистрации пользователя.

   function yourmodule_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'user_register_form') {
            $form['#submit'][] = 'mycustom_user_profile_form_submit';
        }
    }

, А затем программно назначьте значение вашему полю profile_picture, как показано ниже.

function mycustom_user_profile_form_submit($form, &$form_state) {
    if ($form ['field_gender']['und']['#value'] == "Male") {
        $image_path = 'public://pictures/male.jpg';
    } else if ($form ['field_gender']['und']['#value'] == "Female") {
        $image_path = 'public://pictures/female.jpg';
    } else if ($form ['field_gender']['und']['#value'] == "Prefer not to say") {
        $image_path = 'public://pictures/other.jpg';
    }
    $result = db_query("SELECT f.fid FROM {file_managed} f WHERE f.uri = :uri", array(':uri' => $image_path));
    $record = $result->fetchObject();
    $image_info = image_get_info($image_path);
    $fid = 0;
    $account = user_load($form_state['values']['uid']);

    //check if file is already in file_managed table
    if ($record) {
        $fid = $record->fid;
    } else {

        //create new file
        $file = new StdClass();
        $file->uid = $account->uid;
        $file->uri = $image_path;
        $file->filemime = $image_info['mime_type'];
        $file->status = 0;
        $file->filesize = $image_info['file_size'];
        file_save($file);
        $fid = $file->fid;
    }

    //create file array
    $file_array = array();
    $file_array['fid'] = $fid;
    $file_array['display'] = 1;
    $file_array['height'] = $image_info['height'];
    $file_array['weight'] = $image_info['width'];


    $account->field_profile_picture['und'][0] = $file_array;

    user_save($account);
}
 2
Author: Ajinkya Kulkarni, 2012-07-25 21:01:01

Вы можете использовать hook_field_attach_submit() в качестве этот хук вызывается после того, как модуль поля выполнил операцию.

Полностью реализованный код выглядит следующим образом

/**
 * Implements hook_field_attach_submit().
 */
function MODULE_NAME_field_attach_submit($entity_type, $entity, $form, &$form_state) {

    // First find the image fields. This proces is much more complicated than
    // it probably should be.
    // 1. Grab the name of the entity bundle
    // 2. Grab the list of fields for the given entity type and bundle
    // 3. Loop through all fields in that type and bundle and get the image
    //    fields names.
    $entity_info = entity_get_info($entity_type);

    // User entity doesn't have a bundle. So you just pass the type into the
    // bundle field.
    if (empty($entity_info['entity keys']['bundle'])) {
        $field_instances_info = field_info_instances($entity_type, $entity_type);
    }
    else {
        $field_instances_info = field_info_instances($entity_type, $entity->{$entity_info['entity keys']['bundle']});
    }

    $image_fields = array();

    foreach ($field_instances_info as $field_name => $field_instance_info) {
        if($field_name == 'field_profile_picture') {
            $field_info = field_info_field($field_name);
            $image_fields[$field_name] = $field_instance_info['settings'];
            $image_fields[$field_name]['uri_scheme'] = $field_info['settings']['uri_scheme'];
            $image_fields[$field_name]['empty'] = ($form[$field_name]['und'][0]['#value']['fid'] > 0)? FALSE:TRUE;
            $image_fields[$field_name]['default_images_path'] = "default_images";
            $image_fields[$field_name]['gender'] = $form['field_gender']['und']['#value'];

        }
    }
    // The list of image fields is now available. If the instance setting of that
    // field has random_default set and the image field is empty choose a random
    // file of the supported file type in the directory.
    foreach ($image_fields as $field_name => $field_instance_info) {
        if ($field_instance_info['empty']) {

            if($field_instance_info['gender'] == 'Male') {
                $file_selection = cf_get_image_info("public://default_images/avatar-male.jpg");
            }
            else {
                $file_selection = cf_get_image_info("public://default_images/avatar-female.jpg");

            }

            // 2. Check if a file id exists for it
            $result = db_select('file_managed', 'fm')
                ->fields('fm', array('fid'))
                ->condition('fm.uri', $file_selection['uri'])
                ->execute()
                // Fetch as array
                ->fetchAll(PDO::FETCH_ASSOC);

            // 3. If it does not create a new one
            if (empty($result)) {
                GLOBAL $user;
                $file = new stdClass();
                $file->uid = $user->uid;
                $file->filename = $file_selection['filename'];
                $file->uri = $file_selection['uri'];
                $file->filemime = file_get_mimetype($file_selection['uri'], $mapping = NULL);
                $file->status = 1;

                file_save($file);
            }
            else {
                $file = file_load($result[0]['fid']);
            }

            // Add a fake file usage to prevent files pulled form the random directory
            // from being deleted when they are no longer referenced.
            $usage = file_usage_list($file);
            if (!isset($usage['profile_default_image'])) {
                file_usage_add($file, 'profile_default_image', 'profile_default_image', 0);
            }

            // 4. Identify this file for the field
            $entity->{$field_name}['und'][0] = (array) $file;
        }
    }
}


function cf_get_image_info($path) {
    $image1 = image_get_info($path);
    $image2 = pathinfo($path);
    $image_info = array_merge($image1, $image2);
    $image_info['uri'] = $path;

    return $image_info;
}
 1
Author: Sukhjinder Singh, 2015-08-14 08:02:06

Как насчет переопределения template_preprocess_user_picture()?

--> Вот реализация по умолчанию: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/template_preprocess_user_picture/7

Обратите внимание, что здесь принимается решение использовать изображение, предоставленное пользователем, или вернуться к изображению по умолчанию:

[...]

elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}

[...]

Вы могли бы просто расширить это, чтобы опросить гендерное поле, присутствующее в объект $account (который доступен в то время) и предоставляет user_picture_default_male и user_picture_default_female.

Имеет ли это смысл?

 0
Author: jpoesen, 2012-07-22 09:52:03

Другое решение: (используя профиль 2) создайте user-picture.tpl.php в папке вашей темы затем попробуйте выполнить приведенный ниже код.

<?php if ($user_picture) {?>
<div class="<?php print $classes; ?>">
    <?php print $user_picture; ?>
</div>

    <?php 


} else {
$profile = profile2_load_by_user($account->uid);


global $language ;
$curr_lang = $language->language;

if ($profile['main']->field_user_gender) {
$field_user_gender = $profile['main']->field_user_gender['und'][0]['value'];
$uid = $profile['main']->uid;

}
if($field_user_gender=="female"){
?>

        <div class="user-picture">
            <a href="/<?=$curr_lang?>/user/<?=$uid?>" class="active"><img src="/sites/all/themes/xxx/img/f.jpg"></a>

        </div>
        <?php }else{?>
            <div class="user-picture">
                <a href="/<?=$curr_lang?>/user/<?=$uid?>" class="active"><img src="/sites/all/themes/xxx/img/m.jpg"></a>
            </div>
            <?php
}
} ?>
 0
Author: brainHax, 2016-01-13 08:45:32