Sam Fonseca Sam Fonseca - 1 month ago 14
PHP Question

Show or hide HTML code based on URL

I am working on a form and I've stumbled upon a problem. I have different users in which I want them to see different values for one of my SELECT tags; so far I am using PHP to get the URL and if $field == 'donor' then it takes off some of the options. Here's the code:

function defineUser($field){
if(isset($_GET['user']) && urldecode($_GET['user'])){
$field = urldecode($_GET['user']);
if($field == "donor"){
return "<p>
<label for=designation>Designation</label>
<select name='merchant_defined_field_4' id='merchant_defined_field_4' required=''>
<option value=''>Select...</option>
<option value=''>Option 1</option>
<option value=''>Option 2</option>
<option value=''>Option 3</option>
<option value='Other'>Option 4</option>
</select>
</p>";
} else if ($field != "donor") {
return "<p>
<label for=designation>Designation</label>
<select name='merchant_defined_field_4' id='merchant_defined_field_4' required=''>
<option value=''>...</option>
</select>
</p>";
} else {
return "<p>
<label for=designation>Designation</label>
<select name='merchant_defined_field_4' id='merchant_defined_field_4' required=''>
<option value=''>...</option>
</select>
</p>";
}
}
}


This is my function, now on the page source itself I simply have,

<?php echo defineUser($_GET['user']); ?>


My question simply is how can I get each user to see a standard options set - inside my select tag - based on the URL the user has been sent from?

Answer

Your code could be simplified:

function defineUser() {
    $user = isset($_GET['user']) ? urldecode($_GET['user']) : null;

    switch ($user) {
        case 'donor':
            return "<p>
                    <label for=designation>Designation</label>
                    <select name='merchant_defined_field_4' id='merchant_defined_field_4' required=''>
                        <option value=''>Select...</option>
                        <option value=''>Option 1</option>
                        <option value=''>Option 2</option>
                        <option value=''>Option 3</option>
                        <option value='Other'>Option 4</option>
                    </select>
                    </p>";
            break;

        default:
            return "<p>
                    <label for=designation>Designation</label>
                    <select name='merchant_defined_field_4' id='merchant_defined_field_4' required=''>
                        <option value=''>...</option>
                    </select>
                    </p>";
    }
}

You don't need to pass it $_GET['user'] since that is globally accessible, unless you're worried about dependency. Second, you were essentially repeating the same block of HTML twice in your if else clause, using a switch here makes more sense.