Back to PhocacartRegion class

Method getAllRegionsSelectBox

public static
getAllRegionsSelectBox
(mixed $name, mixed $id, mixed $activeArray, mixed $javascript = NULL, mixed $order = 'id')

Method getAllRegionsSelectBox - Source code

public static function getAllRegionsSelectBox($name, $id, $activeArray, $javascript = NULL, $order = 'id')
{
    $db = Factory::getDBO();
    /*$query = 'SELECT a.id AS value, a.title AS text'
    				.' FROM #__phocacart_countries AS a'
    				. ' ORDER BY '. $order;
    		$query = 'SELECT a.id AS value, a.title AS text, a.country_id as countrid'
    				.' FROM #__phocacart_regions AS a'
    				. ' ORDER BY '. $order;*/
    $query = 'SELECT a.id AS value, a.title AS text, a.country_id as cid, c.title as countrytext' . ' FROM #__phocacart_regions AS a' . ' LEFT JOIN #__phocacart_countries AS c ON c.id = a.country_id' . ' ORDER BY c.id, a.' . $order;
    $db->setQuery($query);
    $regions = $db->loadObjectList();
    //$regionsO = JHtml::_('select.genericlist', $regions, $name, 'class="form-control" size="4" multiple="multiple"'. $javascript, 'value', 'text', $activeArray, $id);
    // Try to do 1 SQL Query and 1 Foreach
    $prev = 0;
    // the id of previous item
    $usedFirst = 0;
    // first time opened the optgroup, so we can close it next time when cid is differnt to prev
    $open = 0;
    // if we reach the end of foreach, we discover if the tag is open, if yet, close it.
    $countRegions = count($regions);
    $regionsO = '';
    $regionsO .= '<select id="' . $id . '" name="' . $name . '" class="form-control" size="4" multiple="multiple">';
    $i = 0;
    foreach ($regions as $k => $v) {
        $selected = '';
        if (in_array((int) $v->value, $activeArray)) {
            $selected = 'selected="selected"';
        }
        // Groups
        if ((int) $v->cid > 0 && $v->cid != $prev) {
            if ($usedFirst == 1) {
                $regionsO .= '</optgroup>';
                $open = 0;
            }
            $regionsO .= '<optgroup label="' . $v->countrytext . '">';
            $prev = (int) $v->cid;
            // we prepare previous version
            $usedFirst = 1;
            // we have used the optgroup first time
            $open = 1;
        }
        $regionsO .= '<option value="' . (int) $v->value . '" ' . $selected . '>' . $v->text . '</option>';
        $i++;
        if ((int) $v->cid > 0 && $i == $countRegions && $open == 1) {
            $regionsO .= '</optgroup>';
        }
    }
    $regionsO .= '</select>';
    return $regionsO;
}