Класс HTML с <select> - PullRequest
       33

Класс HTML с <select>

0 голосов
/ 03 апреля 2009

Я пытаюсь создать класс Form в PHP. Пока что кнопки <input> работают довольно хорошо. Но ящики <select> поставили меня в тупик. Я пытаюсь найти «общий» способ добавления тегов <option>, и мне не хватает творчества.

Я не прошу кодез, но идеи реализации приветствуются.

Ответы [ 3 ]

4 голосов
/ 03 апреля 2009

Это моя реализация из моего базового фреймворка, который я использую в супер простых проектах:

function select($name, $options = array(), $attrs = array(), $showEmpty = false) {
    $attrs['name'] = $name;
    $attrs['class'] = isset($attrs['class']) ? $attrs['class'] . ' input' : 'input';
    if(isset($this->validation->invalid[$name])) {
        $attrs['class'] .= ' errorinput';
    }       
    $opts = array();
    foreach($attrs as $key => $value) {
        $opts[] = $key . '="' . $value . '"';   
    }
    $htmloptions = array();
    $hasSelected = false;
    foreach($options as $option => $value) {
        if(isset($this->validation->post[$name]) && $this->validation->post[$name] == $option) {
            $hasSelected = true;
            $htmloptions[] = '<option value="' . $option . '" selected>' . $value;  
        } else {
            $htmloptions[] = '<option value="' . $option . '">' . $value;                   
        }
    }
    if($showEmpty) {
        $emptyoption = '<option value=""' . (($hasSelected) ? '' : ' selected') . '>';
        $htmloptions = array_merge($emptyoption, $htmloptions);
    }
    return '<select ' . implode(' ', $opts) . '>' . implode("\n", $htmloptions) . '</select>';
}
1 голос
/ 03 апреля 2009

Вот какая-то функция, которую я сделал некоторое время назад.

function formLabel($id, $text, $attr = array(), $escape = true) {
    $attr['for'] = $id;
    return htmlElement('label', $text, $attr, true, $escape);
}

function formSelect($name, $selected, $options, $attr = array(), $escape = true) {
    $attr['name'] = $name;
    if (!isset($attr['id'])) {
        $attr['id'] = $name;
    }
    $options = formSelectOptions($selected, $options, $escape);
    return htmlElement('select', $options, $attr, true, false);
}

function formSelectOptions($selected = null, $options, $escape = true) {
    if ($escape) {
        $options = escape($options);
    }
    array_walk($options, 'formSelectOption', $selected);
    return implode('', $options);
}

function formSelectOption(&$value, $key, $selected)  {
    if (is_array($value)) {
        $attr['label'] = $key;
        array_walk($value, 'formSelectOption', $selected);
        $value = htmlElement('optgroup', implode('', $value), $attr, true, false);
    } else {
        $attr['value'] = $key;
        if (($selected == $key) &&
            (0 === strcmp($selected, $key)) && 
            ($selected !== null)) {
            $attr['selected'] = 'selected';
        }
        $value = htmlElement('option', $value, $attr, true, false);
    }
}

function escape($val) {
    if (is_array($val)) {
        return array_map('escape', $val);
    }
    return htmlspecialchars($val, ENT_QUOTES);
}

function htmlElement($tag, $value, $attr = null, $end = true, $escape = true) {
    if (!is_array($attr)) {
        $attr = array();
    }
    if ($escape) {
        $value = htmlspecialchars($value);
    }
    return "<$tag" . (!empty($attr) ? ' ' : '') . arrayToAttributes($attr) . ($end ? '' : '/') . '>' . $value . ($end ? "</$tag>" : '');
}

function arrayToAttributes($attr) {
    array_walk($attr, '_arrayToAttributes');
    return implode(' ', $attr);
}
function _arrayToAttributes(&$v, $k) {
        $k = escape($k);
        $t = escape($v);
        $v = "$k=\"$t\"";
}

Некоторые тесты

<html><header><title>Test</title></header>
<body>
<p>
<?php
$arr = array('hoi', 'wee', 'hai', 'Sub' => array('Hi' => 'Hi', 'Lo' => 'Lo'));
echo '<p>', formSelect('aaaa', null, $arr), "</p>\n";
echo '<p>', formSelect('ccc', 'Hi', $arr), "</p>\n";
echo '<p>', formLabel('hello', 'Hello'), ': ', formSelect('hello', 1, $arr), "</p>\n";
?></p>
<p>
<?php
$months = array (1 => 'Januar',
'Februar', 'Mars', 'April', 'Mai',
'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Desember');
echo formLabel('month', 'Month'), ': ', formSelect('month', null, $months), "\n";
echo formLabel('month2', 'Month'), ': ', formSelect('month2', 4, $months), "\n";
?></p>
</body><html>
0 голосов
/ 03 апреля 2009
function array_drop_down($name, $display_fields, $id_fields, $selected_display_field, $misc = ''){
    $array_dd_html = '<select name="'.$name.'" '.$misc.'>';

    for($i = 0; $i < sizeof($id_fields); $i++){
        if($selected_display_field == $display_fields[$i]){
            $array_dd_html.= '<option selected="yes" value="'.$id_fields[$i].'">'.$display_fields[$i].'</option>';
        }
        else{
            $array_dd_html.= '<option value="'.$id_fields[$i].'">'.$display_fields[$i].'</option>';
        }

    }
    $array_dd_html.= '</select>';

    return $array_dd_html;
}

function sql_drop_down($sql_statement, $name, $display_field, $id_field, $selected_field='',$selected_value='', $misc = ''){
    $result = mysql_query($sql_statement);  
    $numOfCols = mysql_num_rows($result);
    $select_html = '<select name="'.$name.'"'. $misc.'>';
    if($numOfCols > 0){
        for($i = 0; $i < $numOfCols; $i++)
        {
            $id = mysql_result($result, $i, $id_field);
            $display = mysql_result($result, $i, $display_field);
            if($selected_value == $id){
                $select_html.= '<option selected="yes" value="'.$id.'">'.$display.'</option>';
            }
            else{
                $select_html.= '<option value="'.$id.'">'.$display.'</option>';
            }
        }
        $select_html.= '</select>';
    }
    else{
        $select_html = "Error Occured...";
    }
    return $select_html;
}

Используйте переменную $ misc для передачи CSS, идентификаторов, javascript или чего-либо еще

...