Добрый день. Подскажите пожалуйста:
В полях профиля добавлено несколько новых полей. Когда юзер логинится, заголовком блока "Входа в систему" становится "логин юзера". Как сделать, чтобы заголовком блока стало значение одного из выбранных мной полей? Спасибо.
Комментарии
Up
Лучше делать через preprocess_block в template.php, тупо заменять
$vars['block']->subject на то что надо. Вопрос как взять поле из профиля
Примерно это может выглядеть так:
<?php function названиетемы_preprocess(&$vars, $hook) {
if (
$hook == 'block') {if (
ваше условие) {$vars['block']->subject = $поле_профиля;
}
?>}
}
Не проверял, но должно работать
Не силен в php. Можно подробней?
Так я тоже не силён.
Для полей профиля оказывается есть свой препроцесс http://api.drupal.org/api/function/template_preprocess_profile_listing/6
Поле теоретически печатается вот так:
<?php
$profile['Contact']['user_website']['#value'] ?>
Это будет работать, если загружен массив юзера (или объект, х.з), то есть в node.tpl.php должно работать, скорее всего будет работать в preprocess_node
Всё равно ничего не понятно=\
Up
case 1:
if ($menu = menu_tree()) {
$block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation');
$block['content'] = $menu;
}
return $block;
В user.module нашел это. Осталось понять, как быть дальше. Хотя может и не то нашел.
Пока решил так:
Это нужный листинг user.module, где в том числе формируется название блока навигации, после входа в систему
<?php function user_block($op = 'list', $delta = 0, $edit = array()) {
global $user;
//Определяем подгрузку полей профиля
if($user->uid > 0) {profile_load_profile($user);}
if ($op == 'list') {
$blocks[0]['info'] = t('User login');
// Not worth caching.
$blocks[0]['cache'] = BLOCK_NO_CACHE;
$blocks[1]['info'] = t('Navigation');
// Menu blocks can't be cached because each menu item can have
// a custom access callback. menu.inc manages its own caching.
$blocks[1]['cache'] = BLOCK_NO_CACHE;
$blocks[2]['info'] = t('Who\'s new');
// Too dynamic to cache.
$blocks[3]['info'] = t('Who\'s online');
$blocks[3]['cache'] = BLOCK_NO_CACHE;
return $blocks;
}
else if ($op == 'configure' && $delta == 2) {
$form['user_block_whois_new_count'] = array(
'#type' => 'select',
'#title' => t('Number of users to display'),
'#default_value' => variable_get('user_block_whois_new_count', 5),
'#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
);
return $form;
}
else if ($op == 'configure' && $delta == 3) {
$period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
$form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
$form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
return $form;
}
else if ($op == 'save' && $delta == 2) {
variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
}
else if ($op == 'save' && $delta == 3) {
variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
}
else if ($op == 'view') {
$block = array();
switch ($delta) {
case 0:
// For usability's sake, avoid showing two login forms on one page.
if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
$block['subject'] = t('User login');
$block['content'] = drupal_get_form('user_login_block');
}
return $block;
case 1:
if ($menu = menu_tree()) {
//Стандартный вывод $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation'); меняем на вывод того поля, которое нам нужно
$block['subject'] = $user->uid ? check_plain($user->profile_имя поля) : t('Navigation');
$block['content'] = $menu;
}
return $block;
case 2:
if (user_access('access content')) {
// Retrieve a list of new users who have subsequently accessed the site successfully.
$result = db_query_range('SELECT uid, name FROM {users} WHERE status != 0 AND access != 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5));
while ($account = db_fetch_object($result)) {
$items[] = $account;
}
$output = theme('user_list', $items);
$block['subject'] = t('Who\'s new');
$block['content'] = $output;
}
return $block;
case 3:
if (user_access('access content')) {
// Count users active within the defined period.
$interval = time() - variable_get('user_block_seconds_online', 900);
// Perform database queries to gather online user lists. We use s.timestamp
// rather than u.access because it is much faster.
$anonymous_count = sess_count($interval);
$authenticated_users = db_query('SELECT DISTINCT u.uid, u.name, s.timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
$authenticated_count = 0;
$max_users = variable_get('user_block_max_list_count', 10);
$items = array();
while ($account = db_fetch_object($authenticated_users)) {
if ($max_users > 0) {
$items[] = $account;
$max_users--;
}
$authenticated_count++;
}
// Format the output with proper grammar.
if ($anonymous_count == 1 && $authenticated_count == 1) {
$output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', 'count users'), '%visitors' => format_plural($anonymous_count, '1 guest', 'count guests')));
}
else {
$output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', 'count users'), '%visitors' => format_plural($anonymous_count, '1 guest', 'count guests')));
}
// Display a list of currently online users.
$max_users = variable_get('user_block_max_list_count', 10);
if ($authenticated_count && $max_users) {
$output .= theme('user_list', $items, t('Online users'));
}
$block['subject'] = t('Who\'s online');
$block['content'] = $output;
}
return $block;
}
}
}
?>
Вопрос, не повлияют ли мои изменения на безопасность. И сейчас пойду искать, где идет проверка на вводимые в поля значения, т.к. мне нужно, чтобы в поля профиля вводились только буквы (хотя может это ораничение уже и стоит, пока не проверял)
Для удобства понимания:
Были добавлены следующие строки
1) if($user->uid > 0) {profile_load_profile($user);}
2) Стандартный вывод названия блока $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation'); был изменен на $block['subject'] = $user->uid ? check_plain($user->profile_имя поля) : t('Navigation');
Проверка на имя пользователя в user.module делается так
<?php function user_validate_name($name) {
if (!strlen($name)) {
return t('You must enter a username.');
}
if (substr($name, 0, 1) == ' ') {
return t('The username cannot begin with a space.');
}
if (substr($name, -1) == ' ') {
return t('The username cannot end with a space.');
}
if (strpos($name, ' ') !== FALSE) {
return t('The username cannot contain multiple spaces in a row.');
}
if (preg_match('/[^\x{80}-\x{F7} a-z0-9@_.\'-]/i', $name)) {
return t('The username contains an illegal character.');
}
if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP
'\x{AD}'. // Soft-hyphen
'\x{2000}-\x{200F}'. // Various space characters
'\x{2028}-\x{202F}'. // Bidirectional text overrides
'\x{205F}-\x{206F}'. // Various text hinting characters
'\x{FEFF}'. // Byte order mark
'\x{FF01}-\x{FF60}'. // Full-width latin
'\x{FFF9}-\x{FFFD}'. // Replacement characters
'\x{0}-\x{1F}]/u', // NULL byte and control characters
$name)) {
return t('The username contains an illegal character.');
}
if (drupal_strlen($name) > USERNAME_MAX_LENGTH) {
return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
}
}?>
Осталось тоже самое прикрутить к полям профиля ну и при необходимости поднастроить.
Нельзя ядро трогать, используйте препроцесс
Знать бы как=) Я понимаю, почему ядро трогать не стоит, но ничего интересней я пока придумать не смог=\
Остается вопрос, как переопределить эту функцию из user.module
<?php function user_block($op = 'list', $delta = 0, $edit = array())?>
Up