Способы темизации exposed-форм

Главные вкладки

Аватар пользователя jason32 jason32 13 июля 2009 в 11:52

Часто сталкиваешься с ситуацией, когда форма , сделанная через Views - "Exposed Filter"-форма - выглядит совсем не так как надо. Какие есть нормальные способы темизации таких форм, кроме как прописывать CSS стилям, что не всегда удается.Не смог найти никаких доков на оффсайте, в коде всё очень сурово - сплошные циклы, нормально править можно только патчами( или как радикальный способ руками ссоздавать код формы и засовывать его в блок). Где бы почитать про способы переопределения таких форм?

Комментарии

Аватар пользователя gorr gorr 13 июля 2009 в 14:00

Все стандартно вроде...
Во вьюзе есть темплит для формы фильтров views-exposed-form.tpl.php.
Вот то, что в нем лежит:


<?php
// $Id: views-exposed-form.tpl.php,v 1.4 2008/05/07 23:00:25 merlinofchaos Exp $
/**
 * file views-exposed-form.tpl.php
 *
 * This template handles the layout of the views exposed filter form.
 *
 * Variables available:
 * - $widgets: An array of exposed form widgets. Each widget contains:
 * - $widget->label: The visible label to print. May be optional.
 * - $widget->operator: The operator for the widget. May be optional.
 * - $widget->widget: The widget itself.
 * - $button: The submit button for the form.
 *
 * ingroup views_templates
 */
?>
<?php 
if (!empty($q)): ?>
  <?php
    
// This ensures that, if clean URLs are off, the 'q' is added first so that
    // it shows up first in the URL.
    
print $q;
  
?>
<?php 
endif; ?>
<div class="views-exposed-form">
  <div class="views-exposed-widgets clear-block">
    <?php foreach($widgets as $id => $widget): ?>
      <div class="views-exposed-widget">
        <?php if (!empty($widget->label)): ?>
          <label>
            <?php print $widget->label?>
          </label>
        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>
          <div class="views-operator">
            <?php print $widget->operator?>
          </div>
        <?php endif; ?>
        <div class="views-widget">
          <?php print $widget->widget?>
        </div>
      </div>
    <?php endforeach; ?>
    <div class="views-exposed-widget">
      <?php print $button ?>
    </div>
  </div>
</div>
?>

А переменные в него приходят из функции template_preprocess_views_exposed_form(&$vars).
Вот она:

<?php
/**
 * Default theme function for all filter forms.
 */
function template_preprocess_views_exposed_form(&$vars) {
  
views_add_css('views');
  
$form = &$vars['form'];

  

// Put all single checkboxes together in the last spot.
  
$checkboxes '';

  if (!empty(

$form['q'])) {
    
$vars['q'] = drupal_render($form['q']);
  }

  

$vars['widgets'] = array();
  foreach (
$form['#info'] as $id => $info) {
    
// Set aside checkboxes.
    
if (isset($form[$info['value']]['#type']) && $form[$info['value']]['#type'] == 'checkbox') {
      
$checkboxes .= drupal_render($form[$info['value']]);
      continue;
    }
    
$widget = new stdClass;
    
// set up defaults so that there's always something there.
    
$widget->label $widget->operator $widget->widget NULL;

    if (!empty(

$info['label'])) {
      
$widget->label $info['label'];
    }
    if (!empty(
$info['operator'])) {
      
$widget->operator drupal_render($form[$info['operator']]);
    }
    
$widget->widget drupal_render($form[$info['value']]);
    
$vars['widgets'][$id] = $widget;
  }

  

// Wrap up all the checkboxes we set aside into a widget.
  
if ($checkboxes) {
    
$widget = new stdClass;
    
// set up defaults so that there's always something there.
    
$widget->label $widget->operator $widget->widget NULL;
    
$widget->widget $checkboxes;
    
$vars['widgets']['checkboxes'] = $widget;
  }

  

// Don't render these:
  
unset($form['form_id']);
  unset(
$form['form_build_id']);
  unset(
$form['form_token']);

  

// This includes the submit button.
  
$vars['button'] = drupal_render($form);
}
?>

Соответственно, создав в своей теме темплит с таким же названием views-exposed-form.tpl.php, можем его править как хотим, передаваемые в него переменные тоже можем изменить, сделав в template.php функцию function phptemplate_preprocess_views_exposed_form(&$vars).

Аватар пользователя gorr gorr 13 июля 2009 в 15:50

А еще перекрывал exposed_filters с помощью хука form_alter. Делал например следующее: допустим у нас есть фильтр нод по среднему баллу, полученному с помощью fivestar модуля. Что там выходит? А там у меня было установлено пять звездочек при голосовании, а при выведении в фильтр выводились проценты - 20, 40, 60, 80, 100.
Не очень...а хотелось, чтобы в селекте были кол-ва звездочек( вот так - *, **, ***, ****, ***** и отбирались ноды, со средним баллом >= соответствующего.
Делается так:


<?php
function mytools_form_alter(&$form$form_state$form_id) {
  if(
$form_id == 'views_exposed_form' && $form_state['view']->name == 'MY_VIEW_NAME') {
    
$form['average'] = array(
      
'#type' => 'select',
      
'#options' => array(=> t('<any>'), 20 => '*'40 => '**'60 => '***'80 => '****'100 => '*****'),
      
'#default_value' => 0,
      
'#title' => t('The average vote is more than'),
    );

  }
}

?>

В этом коде следует отметить $form_state['view']->name - там лежит имя вьюза, 'average' - это название фильтра по среднему баллу у меня, у вас будет что-то свое.
Вот что получилось:
http://dance-league.com/lessons