I have a form and a drop down menu for users to select Industy Job Sectors as part of their search, e.g. Accountancy, Construction, Engineering etc.
I've searched this forum for solutions regarding how to remember menu select option values AFTER submit and I'm grateful to have implemented a modified version from the solution I found here: Simpliest way to remember DropDown selection?
//For example
if(is_post_request()) {
$jobsector['jobsector_id'] = $_POST['jobsector_id'] ?? '';
} else {
$jobsector['jobsector_id'] = '';
}
<div class="form-group">
<label for="jobsector">Job Sector:</label>
<select class="custom-select" name="jobsector_id" id="jobsector_id">
<option value="">Select Sector</option>
<?php
$query = "SELECT jobsectors.id, jobsectors.jobsector_name FROM jobsectors";
$results = mysqli_query($db, $query);
$_SESSION['jobsector_id'] = $jobsector['jobsector_id'];
$_POST['jobsector_id'] = $_SESSION['jobsector_id'];
//loop
foreach ($results as $jobsector): ?>
<option value="<?php echo h($jobsector['jobsector_name']); ?>"
<?php if ($jobsector['jobsector_name'] == $_POST['jobsector_id']){echo " selected";}?>>
<?= $jobsector['jobsector_name']; ?>
</option>
<?php endforeach;
unset ($_SESSION['jobsector_id']); ?>
</select>
</div>
However, I've run in to a problem where the menu select option values that I have, BEFORE the form is submitted, now show a notice/error:
Notice: Undefined index: jobsector_id
Here's a screen grab: screenshot of undefined index notice
I realise that this will be because the POST value for 'jobsector_id' has not yet been submitted with the form, so my question is how do I get the menu select options to show in the drop down without this error, BEFORE the form is submitted?
I've added a session to store the value of 'jobsector_id' and then made $_POST['jobsector_id'] = $_SESSION['jobsector_id'] and finally unset the session. It all seems to work fine now. Thank you for your suggestions guys!