Search code examples
phpcodeigniter-2

Pass a variable from one page to another in CodeIgniter


In codeigniter, on the page /categories I have a table with the rows of all category items. There is a <select> box to filter the categories by components:

<form accept-charset="utf-8" method="post" action="/categories/get_categories">
    <select onchange="this.form.submit()" name="selectCatsByComponent">
        <option value="0" selected="selected">-- Choose a component --</option>
        <option value="1">Content</option>
        <option value="2">E-commerce</option>
    </select>
</form>

So whenever i select an <option> from the <select> list , and I click on the button ADD NEW CATEGORY, i want to pass that POST value into the next page and automatically select the corresponding component id in the same <select> list.

I tried this but it seems not working:

    if( $this->input->post('selectCatsByComponent') )
        $com_id = $this->input->post('selectCatsByComponent');

Any tips ?

======= UPDATE =======

Guys, for those who are still in searching for a solution - check out my Template Library on GitHub:

https://github.com/danieltorscho/CI_Template_lib

it does what you need, nothing, less, nothing more.


Solution

  • I guess the options have to use a check when the select is written.

    <?php
    /* Use a default, and try to get the value of the previous selection. */
    $com_id = 0;
    if( $this->input->post('selectCatsByComponent') )
        $com_id = $this->input->post('selectCatsByComponent');
    
    $catsByComponentOptions = Array('-- Choose a component --','Content', 'E-commerce');
    ?>
    
    /* start the form */
    <form accept-charset="utf-8" method="post" action="/categories/get_categories">
        <select onchange="this.form.submit()" name="selectCatsByComponent">
    
    <?php 
    /* write out each option, checking to see if it needs to be selected. */
    foreach ($catsByComponentOptions as $key => $value){
        echo '<option value="'. $key .'" ';
        if ($key === '$com_id')
            echo ' selected="selected" '; 
        echo ">$value</option>";
    }
    ?>
    
    </form>