Search code examples
phpdrop-down-menuconcrete5

Reset dropbox automatically to first value after the users hit submit button PHP


After the user hits the submit button, how do I reset the drop down menu to the "blank" option of the the menu? I am using a MVC set up with php and HTML, and the concrete5 library. THANKS IN ADVANCE! Here is what I have so far:

Controller code:

public function authorize() {
    $selectHost = array('' => '');
    foreach ($this->host->getHostInfo() as $row) {
        if (isset($row['HARDWARE_id'])) {
            $selectHost[$row['id']] = $row['host'];
        }
    }
    $this->set('selectHost',$selectHost);
    $postCheck=array(array('param' => 'host',
                           'check' => '^[0-9]{1,50}$',
                           'error_msg' => 'Invalid Host ID'),
    );
    $post = scrub($_POST,$postCheck);
    if (isset($post['host'])) {
        $this->host->authorize($post['host']);
        $this->set('test', "<p>  The host has successfully been authorized.</p>");
    }
    else{
        $this->set('failed', "<p>Invalid Host ID</p>");
    }
}

view code:

<form method="post" enctype="multipart/form-data" action="<?=$this->action('authorize')?>">
<?php
    $form = Loader::helper('form');
    print $form->label('host', 'Host: ');
    print $form->select('host', $selectHost);
?>
<?php   
    print $form->submit('Submit','Submit');
    echo $test;
    echo $failed;
?>
</form>

Solution

  • I'm pretty positive that there's no way to override C5's desire to take the POSTed value and use that as the default. Even if, as TWR suggested, you specify a value. (This is typically a good thing, because if the page is POSTed to and there's an error, you don't want to show the value from the database; you want to show what was in the POST).

    You can override the form helper pretty easily.

    However, I'd suggest that you do a redirect after successful submission (don't redirect after an error -- then the POSTed value will be useful) to a page. You can redirect to another page, or the same one, ideally with a confirmation message. See https://github.com/concrete5/concrete5/blob/master/web/concrete/core/controllers/single_pages/dashboard/blocks/stacks.php#L23 for an example of using redirect.

    This is the best practice for your problem but also because, with your current code, if somebody hits refresh, it'll rePOST the data and reauthorize the host.