Reusing form for input and edit with pulldown menu

Hi,
I have a form which I use for both inputting and editing data.
This works fine for data that is just a text or a number. But how should I deal with a pulldown menu?
When I edit the data I would like to see the current value but also have the option of changing.
Here is my form.html.php As you can see I have made an attempt with the first menu which is the unit menu, but I know that it is incorrect. For the other non pulldown forms I can just use,

value=“<?php htmlout($part);?>”

and so value will either be an empty string ’ ’ when the form is used for input or the actual value if the form is being used for editing.
Here is the form.html…php

<?php include_once $_SERVER['DOCUMENT_ROOT'] .
    '/artgibney/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title><?php htmlout($pageTitle); ?></title>
  <style>
table,th,td
{
border-collapse:collapse;
}
th, td
{
padding:6px;
}
        td { text-align: center; width: 40px; overflow: hidden;  white-space: nowrap;}
        tr.separated {
              border-top: 1px solid black;
                     }
</style>
  </head>
  <body>
  <p><a href="..">physCMS home</a> &#8658; <a href="/artgibney/admin/teachingpoints/">Teaching Points</a></p>
    <h1>Add teaching points</h1>
    <form action="?<?php htmlout($action); ?>" method="post">
      <table>
      <th>Unit</th>
      <th>Year</th>
      <th>Exam</th>
      <th>Question</th>
      <th>Part</th>
      <th>Sub-part</th>
      <th>Curr No.</th>
      <th>Question type</th>
      <tr>
      <td>
                  <?php if($unit == ''):?>
                            <select id="unit" name="unit">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>                  
                            </select>
                         <?php elseif: ?>
                            <?php $value = $unit; ?>
                            <select id="unit" name="unit">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>                  
                            </select>
                         <?php endif;?>
      </td>
      <td>
                            <select id="year" name="year">
                            <option value="2009">2009</option>
                            <option value="2010">2010</option>
                            <option value="2011">2011</option>
                            <option value="2012">2012</option>
                            <option value="2013">2013</option>
                            <option value="2014">2014</option> 
                            <option value="2015">2015</option>                 
                            </select>
      </td>
      <td>
                            <select id="exam" name="exam">
                            <option value="January">January</option>
                            <option value="June">June</option>                 
                            </select>
      </td>
      <td>
        <input type="number" name="question" min="1" max="22" value="<?php htmlout($question);?>">
      </td>
      <td>
        <input type="text" name="part" value="<?php htmlout($part);?>">
      </td>
      <td>
        <input type="text" name="subpart" value="<?php htmlout($subpart);?>">
      </td>
      <td>
        <input type="number" name="currno" min="1" max="138" value="<?php htmlout($currno);?>" >
        <!-- <textarea id="currno" name="topic" rows="1" cols="5"><?php htmlout($currno); ?></textarea>
        <input type="hidden" name="id" value="<?php htmlout($id); ?>"> -->
      </td>
      <td>
        <!-- <input type="tex" name="questiontype"> -->
                <select id="questiontype" name="questiontype">
                  <option value="multiplechoice">Multiple choice</option>
                  <option value="calculation">Calculation</option>
                  <option value="shortanswer">Short answer</option>   
                  <option value="longanswer">Long answer</option>       
                </select>
      </td>
      </tr>
      </table>
      <table>
      <th>Topic</th>
      <th>Sub-topic</th>
      <th>Teaching point</th>
      <tr>
      <td>
        <textarea id="topic" name="topic" rows="3" cols="40"><?php htmlout($topic); ?></textarea>
      </td>
      <td>
        <textarea id="subtopic" name="subtopic" rows="3" cols="40"><?php htmlout($subtopic); ?></textarea>
      </td>
      <td>
        <textarea id="tp" name="tp" rows="3" cols="40"><?php htmlout($tp); ?></textarea>
      </td> 
      </tr>
      </table>
        <input type="submit" value="<?php htmlout($button); ?>">
    </form>
  </body>
</html>

And here is an excerpt from my controller index.php

if (isset($_GET['add']))
{
  $pageTitle = 'New Topics';
  $action = 'addform';
  $unit = '';
  $year = '';
  $exam = '';
  $question = '';
  $part = '';
  $subpart = '';
  $currno = '';
  $topic = '';
  $subtopic = '';
  $tp = '';
  $questiontype = '';
  $id = '';
  $button = 'Add topics';

  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $result = $pdo->query('SELECT id, unit, year, exam, question, part, subpart, currno, topic, subtopic, tp, questiontype FROM teachingpts');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching data from teachingpoints addddd table.';
    include 'error.html.php';
    exit();
  }
  include 'form.html.php';
  exit();
}

if (isset($_GET['addform']))
{
  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $sql = 'INSERT INTO teachingpts SET
        id = :id,
        unit = :unit,
        year = :year,
        exam = :exam,
        question = :question,
        part = :part,
        subpart = :subpart,
        currno = :currno,
        topic = :topic,
        subtopic = :subtopic,
        tp = :tp,
        questiontype = :questiontype';
    $s = $pdo->prepare($sql);
    //$s->bindParam(':id', $_POST['id']);
    $s->bindParam(':id', $_POST['id']);
    $s->bindParam(':unit', $_POST['unit']);
    $s->bindParam(':year', $_POST['year']);
    $s->bindParam(':exam', $_POST['exam']);
    $s->bindParam(':question', $_POST['question']);
    $s->bindParam(':part', $_POST['part']);
    $s->bindParam(':subpart', $_POST['subpart']);
    $s->bindParam(':currno', $_POST['currno']);
    $s->bindParam(':topic', $_POST['topic']);
    $s->bindParam(':subtopic', $_POST['subtopic']);
    $s->bindParam(':tp', $_POST['tp']);
    $s->bindParam(':questiontype', $_POST['questiontype']);
    $s->execute();    
  }
  catch (PDOExceptin $e)
  {
    $error = 'Error adding submitted teachpoints ADDFORM table data.';
    include 'error.html.php';
    exit();
  }

    include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $result = $pdo->query('SELECT id, unit, year, exam, question, part, subpart, currno, topic, subtopic, tp, questiontype FROM teachingpts');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching data from teachingpoints table.';
    include 'error.html.php';
    exit();
  }

  foreach ($result as $row)
  {
 $teachingpts[] = array('id' => $row['id'], 'unit' => $row['unit'], 'year' => $row['year'], 'exam' => $row['exam'], 'question' => $row['question'], 'part' => $row['part'], 'subpart' => $row['subpart'], 'currno' => $row['currno'], 'topic' => $row['topic'], 'subtopic' => $row['subtopic'], 'tp' => $row['tp'], 'questiontype' => $row['questiontype']);
  }
   
  //include 'form.html.php';
  header('Location: .');
  exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'Edit')
{
  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $sql = 'SELECT id, unit, year, exam, question, part, subpart, currno, topic, subtopic, tp, questiontype FROM teachingpts WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindParam(':id', $_POST['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching teachingpoints row details.';
    include 'error.html.php';
    exit();
  }
  $row = $s->fetch();

  $pageTitle = 'Edit a row of the teaching points table';
  $action = 'editform';
  $id = $row['id'];
  $unit = $row['unit'];
  $year = $row['year'];
  $exam = $row['exam'];
  $question = $row['question'];
  $part = $row['part'];
  $subpart = $row['subpart'];
  $currno = $row['currno'];
  $topic = $row['topic'];
  $subtopic = $row['subtopic'];
  $tp = $row['tp'];
  $questiontype = $row['questiontype'];
  $button = 'Update teaching points';

  // Build the list of topic rows
  try
  {
    $result = $pdo->query('SELECT id, unit, year, exam, question, part, subpart, currno, topic, subtopic, tp, questiontype FROM teachingpts');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching list of teaching points.';
    include 'error.html.php';
    exit();
  }

  foreach ($result as $row)
  {
 $teachingpts[] = array('id' => $row['id'], 'unit' => $row['unit'], 'year' => $row['year'], 'exam' => $row['exam'], 'question' => $row['question'], 'part' => $row['part'], 'subpart' => $row['subpart'], 'currno' => $row['currno'], 'topic' => $row['topic'], 'subtopic' => $row['subtopic'], 'tp' => $row['tp'], 'questiontype' => $row['questiontype']);
  }

  include 'form.html.php';
  exit();
}

if (isset($_GET['editform']))
{
  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
  
  try
  {
    $sql = 'UPDATE teachingpts SET
        id = :id,
        unit = :unit,
        year = :year,
        exam = :exam,
        question = :question,
        part = :part,
        subpart = :subpart,
        currno = :currno,
        topic = :topic,
        subtopic = :subtopic,
        tp = :tp,
        questiontype = :questiontype';
    $s = $pdo->prepare($sql);
    $s->bindParam(':id', $_POST['id']);
    $s->bindParam(':unit', $_POST['unit']);
    $s->bindParam(':year', $_POST['year']);
    $s->bindParam(':exam', $_POST['exam']);
    $s->bindParam(':question', $_POST['question']);
    $s->bindParam(':part', $_POST['part']);
    $s->bindParam(':subpart', $_POST['subpart']);
    $s->bindParam(':currno', $_POST['currno']);
    $s->bindParam(':topic', $_POST['topic']);
    $s->bindParam(':subtopic', $_POST['subtopic']);
    $s->bindParam(':tp', $_POST['tp']);
    $s->bindParam(':questiontype', $_POST['questiontype']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error updating submitted teaching points.';
    include 'error.html.php';
    exit();
  }

  header('Location: .');
  exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'Delete')
{
  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  // Delete the joke
  try
  {
    $sql = 'DELETE FROM teachingpts WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':id', $_POST['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error deleting teachingpts table data.';
    include 'error.html.php';
    exit();
  }

  header('Location: .');
  exit();
}

  try
  {
    $result = $pdo->query('SELECT id, unit, year, exam, question, part, subpart, currno, topic, subtopic, tp, questiontype FROM teachingpts');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching list of teacgingpoints.';
    include 'error.html.php';
    exit();
  }

  foreach ($result as $row)
  {
    //$teachingpts[] = array('id' => $row['id'], 'tp' => $row['tp'], 'currno' => $row['currno'], 'unit' => $row['unit']);
    $teachingpts[] = array('id' => $row['id'], 'unit' => $row['unit'], 'year' => $row['year'], 'exam' => $row['exam'], 'question' => $row['question'], 'part' => $row['part'], 'subpart' => $row['subpart'], 'currno' => $row['currno'], 'topic' => $row['topic'], 'subtopic' => $row['subtopic'], 'tp' => $row['tp'], 'questiontype' => $row['questiontype']);
  }

include 'searchform.html.php';

Any help would be greatly appreciated,
thanks,
Shane

I’m not sure I understand the problem. Do you just want a defined option selected by default? If so, you just add selected to the option that has the corresponding value. It’s annoying, I know.

For example, you have this:

<select id="questiontype" name="questiontype">
    <option value="multiplechoice">Multiple choice</option>
    <option value="calculation">Calculation</option>
    <option value="shortanswer">Short answer</option>   
    <option value="longanswer">Long answer</option>       
</select>

What I would do instead is form an associated array of choices:

$options = [
    'multiplechoice'    => 'Multiple Choice',
    'calculation'       => 'Calculation',
    'shortanswer'       => 'Short answer',
    'longanswer'        => 'Long answer'
];

and loop through them, checking the desired value with those in the array:

<select name="questiontype" id="questiontype">
    <?php foreach($options as $key=>$option):
        $selected = ($questiontype == $key) ? 'selected' : '';
        echo "<option value='$key' $selected>$option</option>";
    endforeach; ?>
</select>

Hi,
Thanks for your reply. I was trying this,

 <select id="unit" name="unit">
                            <option selected="selected">
                            <?php htmlout($unit);?>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>                  
                            </select>

But this repeats the selected value. I don’t think this will happen with your method.
I had to reaquainted myself with the ternary operator ? : But I think I see what your code does now. If no key has a value after going through the $options array then set $select equal to the empty string ’ '.
Just going to try it now.
Fantastic, thanks for this,
Shane

Works perfectly,
Thank you very much for this.
Shane

Hi,
I am re-examining this bit of code, which I thought I understood. But I can’t figure out what is the variable $questiontype Is this a dummy variable or some kind of place holder?

</td>
      <?php 
      $questions = ['multiplechoice' => 'Multiple Choice', 'calculation' => 'Calculation', 'shortanswer' => 'Short answer', 'longanswer' => 'Long answer'];
      ?>
      <td>
                <select name="questiontype" id="questiontype">
                     <?php foreach($questions as $key=>$option):
                           $selected = (**$questiontype** == $key) ? 'selected' : '';
                           echo "<option value='$key' $selected>$option</option>";
                      endforeach; ?>
                </select>
      </td>

My understanding of that line with the tenary operator is that it checks that $questiontype is equal to $key and if it is, then $selected is set to ‘selected’ and if $questiontype is not equal to $key then it is set equal to an empty variable ’ '.
Thanks,
Shane

I just grabbed that variable from the list you had above. You would just change it with whatever variable holds the possible values for that select field.

If it helps, this:

$selected = ($questiontype == $key) ? 'selected' : '';

is equivalent to this:

if($questiontype == $key):
    $selected = 'selected';
else:
    $selected = '';    
endif;

or just:

$selected = '';
if($questiontype == $key)
    $selected = 'selected';

Don’t let the ternary operator trip you up though, just use what works for you. I prefer it as it’s easier for me to read through but it’s certainly not “better”!

Hi,
I forgot that $questiontype is an array. But what i also didn’t realise is that when you use foreach to step through each row of an array, in this case $questions, you are also stepping through each row of any array inside the foreach loop.
Thanks for taking the time to explain this, it was driving me a little crazy.
Shane
PS Actually $questiontype is not an array it has a single value, which is whatever question type that question has in the edit form. so therefore the foreach is not stepping through each array inside of it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.