[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

Trouble with Select Box Array

Good Morning Experts,

I have a Joomla installation that I have added a component to called "Easy Calendar"  I have added some fields to the database that we need to capture and in turn have added those fields to the php page that it draws from. The fields that I need to add are drop down boxes and the elements of them pull from an array.

The issue becomes this, when I add a new record everything works. The field drops down and allows a selection and upon save the record gets populated back to the database.

But when I go back to the record to edit it, the drop down box is set back to the default "Please Select" and not the value from the database. So when it gets saved again the entry for that field gets wiped out.

Technical items:

First there are two pages. The events.php and which houses all the arrays and then the actual admin.easycalendar.html.php page that houses the form.


Here is the array from the events.php page:

$dinnerArray = array();
        $dinnerArray[0]->text = "Please Select";
    $dinnerArray[0]->value = "0";
    $dinnerArray[1]->text = "Y";
    $dinnerArray[1]->value = "1";
    $dinnerArray[2]->text = "N";
    $dinnerArray[2]->value = "2";
    $dinnerArray[3]->text = "BFST";
    $dinnerArray[3]->value = "3";
    $dinnerArray[4]->text = "LUNCH";
    $dinnerArray[4]->value = "4";
    $dinnerArray[5]->text = "REF";
    $dinnerArray[5]->value = "5";
    $lists['dinner'] = mosHTML::selectList($dinnerArray, 'dinner', 'class="text_area"', 'value', 'text', $row->dinner);

Here is the information from the admin.easycalendar.html.php page

<?php echo $lists['dinner'] ?>

I know it has something to do with the array, because if I just put a text box in place of the drop down, it works fine. The only thing is I have to manually enter the data into the field.

Any help anyone could provide, would be greatly appreciated.
0
thenakedcherry
Asked:
thenakedcherry
  • 3
  • 3
  • 2
1 Solution
 
Rok-KraljCommented:
Try

for($i=0;$i<count($dinnerArray);++$i) {
echo ('<option value="'.$i.'">');
echo ($dinnerArray[$i].'</option>');
}
0
 
Rok-KraljCommented:
And don't forget select tag:

echo('<select name="country">');
for($i=0;$i<count($dinnerArray);++$i) {
echo ('<option value="'.$i.'">');
echo ($dinnerArray[$i].'</option>');
}
echo('</select>');
0
 
thenakedcherryAuthor Commented:
Rok,

I moved the array to the main page, then I added your code. What it gives me now is a drop down box with five items in it that state "object"

Here is  the code:

<?php
                                    $dinnerArray = array();
                                      $dinnerArray[0]->text = "Please Select";
                                  $dinnerArray[0]->value = "0";
                                  $dinnerArray[1]->text = "Y";
                                  $dinnerArray[1]->value = "1";
                                  $dinnerArray[2]->text = "N";
                                  $dinnerArray[2]->value = "2";
                                  $dinnerArray[3]->text = "BFST";
                                  $dinnerArray[3]->value = "3";
                                  $dinnerArray[4]->text = "LUNCH";
                                  $dinnerArray[4]->value = "4";
                                  $dinnerArray[5]->text = "REF";
                                  $dinnerArray[5]->value = "5";
                                  echo('<select name="dinner">');
                                    for($i=0;$i<count($dinnerArray);++$i) {
                                    echo ('<option value="'.$i.'">');
                                    echo ($dinnerArray[$i].'</option>');
                                    }
                                    echo('</select>');?>
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Rok-KraljCommented:
And what do you want?
0
 
thenakedcherryAuthor Commented:
Well I guess I would like the solution.
0
 
AlexanderRCommented:
Where is $row comming from?

if its comming from a database output similar to

$sqlSelectEvents = "SELECT event_type_id FROM user_events WHERE user_id = xx";
$rsSelectEvents = mysqli_query($db, $sqlSelectEvents);
while ($rwEvents = mysqli_fetch_array($rsSelectEvents)) {
$EventType = $rwEvents["event_type_id"];
}

then you can have
$lists['dinner'] = mosHTML::selectList($dinnerArray, 'dinner', 'class="text_area"', 'value', 'text', $EventType);

Rok-Kralj:
Your solution would be fine if he would be using regular HTML.  He uses Joomla content management system that uses some sophisticated programatic html control generation.  The one in question is at http://help.joomla.org/content/view/500/60/
Apparently he got drop down to display, he just needs a correct value to be selected by default.  Details are on that link.
0
 
thenakedcherryAuthor Commented:
Hello Alexander,

Thanks for the feedback. Yes, I got the drop down to work using that link you provided. That was the easy part. What the issue is now is that when I create the record everything works. It's when i go to edit the record, the list doesn't pull the info from the database it just defaults to the "Please Select".

The component in question has a time select box and this works fine. I was trying to copy it as much as possible but I don't know enough about it to get it to pull right.

If you are interested here is the code from the entire events.php page.

Thanks again.

<?php
/**
* @package Easy Calendar
* @copyright (C) 2006 Joomla-addons.org
* @author Websmurf
*
* --------------------------------------------------------------------------------
* All rights reserved.  Easy Calendar Component for Joomla!
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Creative Commons - Attribution-NoDerivs 2.5
* license as published by the Creative Commons Organisation
* http://creativecommons.org/licenses/by-nd/2.5/.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
* --------------------------------------------------------------------------------
**/

defined( '_VALID_MOS' ) or die( 'Restricted access' );


class events {
 
  /**
   * Show a list of all events
   *
   */
  function show(){
    global $database, $mainframe, $option;
   
    $limit = intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mainframe->getCfg('list_limit') ) );
        $limitstart      = intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
        $cid      = intval( $mainframe->getUserStateFromRequest( "view{$option}cid", 'cid', 0 ) );
        $search      = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
        $search      = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if(!empty($search)){
          $where[] = "name LIKE '%" . $search . "%'";
        }
        if($cid > 0){
          $where[] = 'cid = ' . $cid;
        }
        
        $basequery = "SELECT %s FROM #__easycalendar e
          LEFT JOIN #__categories c ON e.cid = c.id ";
        if(sizeof($where) > 0){
          $basequery .= "WHERE " . implode(" AND ", $where);
        }
        $basequery .= " ORDER BY startdate";
        
        $query = str_replace('%s', 'COUNT(1)', $basequery);
        $database->setQuery($query);
        $total = $database->loadResult();
        
        require_once($mainframe->getCfg('absolute_path') . '/administrator/includes/pageNavigation.php');
        $pageNav = new mosPageNav($total, $limitstart, $limit);
        
        $query = str_replace("%s", "e.*, c.name AS category", $basequery);
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        echo $database->getErrorMsg();
        
        $lists = array();
        
 
        
        $lists['search'] = $search;
        
        $categories = categories::getCategorieTree();
        
        $obj = new stdClass();
        $obj->id = 0;
        $obj->name = ' - all - ';
        
        array_unshift($categories, $obj);
        
        $lists['cid'] = mosHTML::selectList($categories, 'cid', 'onchange="document.adminForm.submit();"', 'id', 'name', $cid);
        
        HTML_easycalendar::showEvents($rows, $pageNav, $lists);
  }
 
  /**
   * Edit an event
   *
   * @param int $id
   */
  function edit($id){
    global $database;
   
    $row = new dbEvent($database);
    $row->load($id);
   
    $lists = array();
   
    $categories = categories::getCategorieTree();
        
        $obj = new stdClass();
        $obj->id = 0;
        $obj->name = ' - select - ';
        
        array_unshift($categories, $obj);
        
        
      $dinnerArray = array();
        $dinnerArray[0]->text = "Please Select";
    $dinnerArray[0]->value = "0";
    $dinnerArray[1]->text = "Y";
    $dinnerArray[1]->value = "1";
    $dinnerArray[2]->text = "N";
    $dinnerArray[2]->value = "2";
    $dinnerArray[3]->text = "BFST";
    $dinnerArray[3]->value = "3";
    $dinnerArray[4]->text = "LUNCH";
    $dinnerArray[4]->value = "4";
    $dinnerArray[5]->text = "REF";
    $dinnerArray[5]->value = "5";
      $lists['dinner'] = mosHTML::selectList($dinnerArray, 'dinner', 'class="text_area"', 'value', 'text', $row->dinner);
      
      
      $pubArray = array();
        $pubArray[0]->text = "Please Select";
    $pubArray[0]->value = "0";
    $pubArray[1]->text = "Y";
    $pubArray[1]->value = "1";
    $pubArray[2]->text = "N";
    $pubArray[2]->value = "2";
    $pubArray[3]->text = "SP";
    $pubArray[3]->value = "3";
    $lists['pub'] = mosHTML::selectList($pubArray, 'pub', 'class="text_area"', 'value', 'text', $row->pub);
        
        $lists['cid'] = mosHTML::selectList($categories, 'cid', 'class="text_area"', 'id', 'name', $row->cid);
        $lists['published'] = mosHTML::yesnoRadioList('published', '', intval($row->published));
        
        $times = array();
        for($i=0;$i<24;$i++){
          $times[] = mosHTML::makeOption((strlen($i) < 2 ? '0'.$i : $i) . ':00:00', $i . ':00');
          $times[] = mosHTML::makeOption((strlen($i) < 2 ? '0'.$i : $i) . ':30:00', $i . ':30');
        }
        
        $lists['starttime'] = mosHTML::selectList($times, 'starttime', 'class="text_area"', 'value', 'text', $row->starttime);
        $lists['endtime'] = mosHTML::selectList($times, 'endtime', 'class="text_area"', 'value', 'text', $row->endtime);
   
    HTML_easycalendar::editEvent($row, $lists);
  }
 
  /**
   * Save event
   *
   */
  function save(){
    global $database, $option, $task;
   
    $row = new dbEvent($database);
    $row->bind($_POST);
   
    if (!$row->check()) {
                  echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
                  exit();
            }
            if (!$row->store()) {
                  echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
                  exit();
            }
            
            switch ($task){
              case 'save':
                mosRedirect('index2.php?option=' . $option . '&act=events', 'Changes to event saved');
                break;
              case 'apply':
                mosRedirect('index2.php?option=' . $option . '&act=events&task=edit&cid=' . $row->id . '&hidemainmenu=1', 'Changes to event saved');
                break;
            }
  }
 
  /**
   * Remove Event(s)
   *
   * @param array ids
   */
  function remove($cid){
    global $database, $option;
   
    $row = new dbEvent($database);
   
    for($i=0,$n=count($cid);$i<$n;$i++){
      $id = $cid[$i];
     
      $row->delete($id);
    }
   
    mosRedirect('index2.php?option=' . $option . '&act=events', 'Selected events removed');
  }
 
  /**
   * Set a Event state
   *
   * @param int id
   * @param int published
   */
  function setState($ids, $published){
    global $database, $option;
   
    $row = new dbEvent($database);
    for($i=0,$n=count($ids);$i<$n;$i++){
      $row->load($ids[$i]);
   
      $row->published = $published;
   
      if (!$row->store()) {
                    echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
                    exit();
              }
    }
   
    mosRedirect('index2.php?option=' . $option . '&act=events');
  }
 
  /**
   * Display all items in the frontend
   *
   * @param int category id
   * @param mosParameters params
   */
  function frontView($cid, $view, $params){
    global $database;
   
    $month = intval(mosGetParam($_REQUEST, 'month', date('m')));
    $year = intval(mosGetParam($_REQUEST, 'year', date('Y')));
   
    $rows = events::getEvents($cid, $view);

//    echo '<pre>';
//    print_r($rows);
//    echo '</pre>';
   
    switch ($view){
      case 'upcoming':
        HTML_easycalendar::showUpcoming($rows);
        break;
      case 'month':
      default:
        HTML_easycalendar::showMonth($rows, $month, $year);
        break;
    }
  }
 
  /**
   * Get all events from a certain category and display them accoording to a certain view
   *
   * @param int $cid
   * @param string $view
   * @return array
   */
  function getEvents($cid, $view){
    global $database;
   
    $where = array();
    $where[] = 'e.published = 1 AND c.published = 1';
    if($cid > 0){
      /** @todo get subcategories and show them as well **/
      $where[] = 'cid = ' . $cid;
    }
    switch ($view){
      case 'upcoming':
        $where[] = '
        (
          (
            DATE(startdate) >= DATE(NOW()) OR
            DATE(enddate) >= DATE(NOW())
          ) AND
          (
            DATE(startdate) <= DATE(DATE_ADD(NOW(), INTERVAL 1 MONTH)) OR
            DATE(enddate) <= DATE(DATE_ADD(NOW(), INTERVAL 1 MONTH))
          )
        )';
        break;
      case 'month':
      default:
        $month = intval(mosGetParam($_REQUEST, 'month', date('m')));
        $year = intval(mosGetParam($_REQUEST, 'year', date('Y')));
       
        $where[] = '((MONTH(startdate) = ' . $month . ' AND YEAR(startdate) = ' . $year . ') OR (MONTH(enddate) = ' . $month . ' AND YEAR(enddate) = ' . $year . '))';
    }
   
    $query = 'SELECT e.*, c.name AS category FROM #__easycalendar e ' . "\n";
    $query .= 'LEFT JOIN #__categories c ON e.cid = c.id ';
    if(sizeof($where) > 0){
      $query .= 'WHERE ' . implode(' AND ', $where) . "\n";
    }
    $query .= 'ORDER BY startdate, starttime';
   
    $database->setQuery($query);
    $rows = $database->loadObjectList();
//    echo $database->getQuery();
    echo $database->getErrorMsg();
   
    $array = array();
    for($i=0,$n=count($rows);$i<$n;$i++){
      $row = $rows[$i];
      switch ($view){
        case 'upcoming':
          $array[] = $row;
          break;
        case 'month':
        default:
          if($row->startdate == $row->enddate){ //nothing special
            if($row->starttime == $row->endtime){
              $array[$row->startdate]['allday'][] = $row;
            } else {
              $array[$row->startdate]['regular'][] = $row;
            }
          }
          else {
            //meerdere dagen
            $start = strtotime($row->startdate . ' 12:00:00');
            $end = strtotime($row->enddate . ' 12:00:00');

            for($j=$start;$j<$end + (60*60*24);$j=$j+(60*60*24)){
              $array[date('Y-m-d', $j)]['allday'][] = $row;
            }
          }
      }
    }
   
    return $array;
  }
 
  /**
   * View details of a certain event
   *
   * @param int $id
   */
  function view($id, $params){
    global $database;
   
    $row = new dbEvent($database);
    $row->load($id);
   
    $row->category = new mosCategory($database);
    $row->category->load($row->cid);
   
    HTML_easycalendar::viewEvent($row, $params);
  }
}

?>

0
 
AlexanderRCommented:
Thank you. Yes i was definetly interested :).

My problem is that i dont know OOP PHP yet. Just procedural. Prety shamefull of me.
However i can still tell that you are not running any queries that pull default information from the database.  You need to run a query that pulls the event set by user in order to get its value and apply to the select box.

See what all it takes to do a propper query?:
 $basequery = "SELECT %s FROM #__easycalendar e
          LEFT JOIN #__categories c ON e.cid = c.id ";
        if(sizeof($where) > 0){
          $basequery .= "WHERE " . implode(" AND ", $where);
        }
        $basequery .= " ORDER BY startdate";
       
        $query = str_replace('%s', 'COUNT(1)', $basequery);
        $database->setQuery($query);
        $total = $database->loadResult();

(just an example in your case it will look completly different)

and you just have
    $row = new dbEvent($database);
    $row->load($id);

That wont do anything......
You need propper SQL statements based on table where you are getting your events stuff from or however you have it set.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now