Search code examples
phpformsisset

Determining if other <option> was selected, or if default "Select one..." with blank value was submitted


I am adding a sort by option to my search page. I am using two select form input type, one for the field to order by, and one for ASC/DESC. I have the first option with value="" and text "Select one...".

<label for="sort[order_by_field]">Field</label><select name="sort[order_by_field]" id="combobox">
    <option value="">Select one...</option>
    <optgroup label="---">
        <option value="finding_incident_number"<?php echo ($field == 'finding_incident_number' ? ' selected="selected"': false); ?>>Incident #</option>
        <option value="finding_violation_type"<?php echo ($field == 'finding_violation_type' ? ' selected="selected"': false); ?>>Finding</option>

<label for="sort[order_by_direction]">Direction</label>
    <select name="sort[order_by_direction]">
    <option>Select one...</option>
    <option value="ASC"<?php echo ($dir == 'ASC' ? ' selected="selected"': false); ?>>Ascending</option>
    <option value="DESC"<?php echo ($dir == 'DESC' ? ' selected="selected"': false); ?>>Descending</option>
    </select>

After submitting my form, I check if isset($_POST['sort']). It is set. I also check for !empty. It is always !empty. I want to know if the user actually made a selection. Is there a way to set this up so that I don't have to check on individual array values, i.e. isset($_POST['sort']['order_by_field'])? I would like to have a dynamic number of addable/removable sort by fields in the future.

I suppose I could use an optiongrp label, but then that wouldn't be semantic markup would it? I guess it would work though.

From a broader perspective, is putting "Select One..." a good practice for a form dropdown?


Solution

  • The select field always will be set in $_POST

    you should check by

    if ($_POST['sort_by']['field_name'] !='')
    

    OR

    if ($_POST['sort_by']['field_name'] != null)
    

    and this is always a good practice to check variable before using them.

    putting "Select One..." is a good practice nothing bad with this.