Search code examples
phpcodeigniterdrop-down-menupersist

Redirect and set_select problem


I am using CodeIgniter 1.7.1.Ok here is the scenario.When ever the form is submitted,i need to do two things

1) persist the value selected in dropdown. 2) using session->set_flashdata(),i need to set the custom database message.

Now as we know,we need to redirect before this flash data can be set.

This is the code which i have written.

if ($this->form_validation->run() == TRUE){

    $this->session->set_flashdata(‘msg’, ‘Taha Hasan’); 
    redirect(current_url());

    $this->ShowReceiveInventoryView();
}

Also i m using set_select in the dropdown view to persist the value.

<select name=“myselect”>
<option value=“one” <?php echo set_select(‘myselect’, ‘one’, TRUE); ?> >One</option>
<option value=“two” <?php echo set_select(‘myselect’, ‘two’); ?> >Two</option>
<option value=“three” <?php echo set_select(‘myselect’, ‘three’); ?> >Three</option>
</select>

Now here is the problem…The flash message appears BUT because i am redirecting to the current page,the drop down set_select value is lost !!! Default value appears in the selection :(..If i remove the redirect line in the code,the dropdown value is presisted but Flash data is not set !!!

Hope you guys have a solution to this problem…


Solution

  • set_select() only works when the $_POST array has content (as you've discovered), but your redirect is obviously a GET request.

    The proper way to handle this is to perform your query within the Controller, passing the object that is being edited to your view. Within your view you then repopulate your form, or set default values, based on $_POST if it exists or based on the passed object.

    Let's assume we are editing a product, which has the myselect (a horribly named field) property. We will use PHP's ternary operator to test if the value of the product's myselect parameter is equal to the current option - if so, we'll use set_selects()'s third parameter to set the default.

    <option value="one" <?php echo set_select('myslect', 'one', ((!$product) || !$this->input->post('myselect') && $product->myselect == 'one' ? TRUE : FALSE); ?>One</option>
    
    <option value="two" <?php echo set_select('myselect', 'two', (!$this->input->post('myselect') && $product->myselect == 'two' ? TRUE : FALSE); ?>Two</option>