Welcome Guest, Not a member yet? Register   Sign In
[SOLVED] Re-populating a select/dropdown list generated from a database table using set_value()
#1

[eluser]edjon2000[/eluser]
Hello all Smile

First of all, I have read through some similar topics on this subject, some of which helped partially with generating the dropdown list in the first place, but I couldn't find an example of re-populating the fields that worked for me, which leads me to suspect that it is probably something I am doing wrong.

This is part of a project I am working on for a client at this moment, so any help with this would be greatly appreciated, I am quite new to CodeIgniter so please be kind Wink

Ok, first of all I needed to generate a list of say, vacancies from a vacancy_list table but for the purposes of the subsequent search on the main table I needed the option values and labels to be the same, after trying various combinations, in my model I used this

Code:
/**
     * The generate_vacancy_list method generates the data to populate
     * the vacancy dropdown menu for the vacancy search form
     *
     * Returned object (array of)
     * --------------------------
     * vac_list_name
     *
     * @return array
     */
    function generate_vacancy_list() {
        /**
         * Generate return array for vacancy field dropdown options
         */
                $vacancy_keys = array();
                $vacancy_keys_arr = array();
                $vacancy_vals_arr = array();

        $vacancy_keys = $this->db->query('SELECT DISTINCT(vac_list_name) FROM vacancy_list ORDER BY vac_list_id');

        foreach ($vacancy_keys->result_array() as $vacancy_key) {
            $vacancy_keys_arr[] = $vacancy_key['vac_list_name'];
            $vacancy_vals_arr[] = $vacancy_key['vac_list_name'];
        }

        $query = array_combine($vacancy_keys_arr, $vacancy_vals_arr);

        return $query;
    }

Now I think there could ba a problem in there, maybe in the way I am constructing the returned results, this is handled by the controller as follows

Code:
/**
     * Vacancy Functions
     */
    function add_vacancy()
    {
        /** rules for form validation **/
        $this->form_validation->set_error_delimiters('<span class="flashError">', '</span>');

        $this->form_validation->set_rules('client_name', 'Client\'s Name', 'trim|required|min_length[3]|max_length[50]');
        $this->form_validation->set_rules('client_address', 'address', 'trim|max_length[1024]');
        $this->form_validation->set_rules('client_phone', 'phone number', 'trim||min_length[3]|max_length[50]');
        $this->form_validation->set_rules('client_email', 'email address', 'trim|min_length[3]|max_length[50]|valid_email');
        $this->form_validation->set_rules('client_postcode', 'postcode', 'trim|min_length[3]|max_length[10]');
        $this->form_validation->set_rules('vacancy_name', 'vacancy', 'trim|required');
        $this->form_validation->set_rules('vacancy_salary', 'salary', 'trim|required');
        $this->form_validation->set_rules('vacancy_sector', 'sector', 'trim|required');
        $this->form_validation->set_rules('vacancy_area', 'location', 'trim|required');
        $this->form_validation->set_rules('vacancy_desc', 'description', 'trim|max_length[5000]');
        $this->form_validation->set_rules('vacancy_active', 'please select an option', 'required');
        $this->form_validation->set_rules('vacancy_featured', 'please select an option', 'required');

        if($this->form_validation->run())
        {
            //load the check vacancy page
        }



        /** rebuild add vacancy page view with errors if unsuccessful **/
        $data = array();
        $data['page_title'] = 'Add New Vacancy';
        $data['main_content_1'] = 'admin_views/admin_add_vac_view';

        $data['vac_name'] = $this->vacancy_model->generate_vacancy_list();

        $data['sec_name'] = $this->vacancy_model->generate_sector_list();
        $data['sal_amount'] = $this->vacancy_model->generate_salary_list();

        $this->load->view('includes/template', $data);
        //echo "<h1>Here is the add new vacancy page</h1>";
    }

Which, in turn, is passed to the view

Code:
<label for="vacancy">Vacancy Name<span class="req">required</span></label>
            &lt;?php    echo form_dropdown('vacancy', $vac_name, set_value('vacancy'), 'id="vacancy"');    ?&gt;

But, for some reason, I cannot get it to re-display the selected field, the actual generated dropdown list works fine and all of the other non-dropdown fields re-display correctly i.e. input text and input textarea fields worked fine, here's an example of the source listing

Code:
<label for="vacancy">Vacancy Name<span class="req">required</span></label>
            <select name="vacancy" id="vacancy">
<option value="All Specialists">All Specialists</option>
...
</select>

My apologies for the long post, but I wanted to supply as much information as possible.

I look forward to your responses
#2

[eluser]sooner[/eluser]
in the form_dropdown function..the third argument is the one which selects the value..in the set_value() function..eg set_value('dynamicvalue','defaultvalue')...the dynamic value should be the one which should be the selected value and the defaultvalue is the one which shows up first time.so in your case set_value('dynamicvalue','vacancy')...you should try to pass the dynamic value may be by form post or there are many ways to do that...
#3

[eluser]edjon2000[/eluser]
Hello sooner, thanks for your reply,

I think this is where my lack of understanding about exactly how the form_validation class works is tripping me up, in a traditional type of design I would use the $_POST['variable'] value to repopulate using something along the lines of
Code:
(isset $_POST['whatever']) ? do this : do that;
however I am not sure at what point the $_POST array is created using CodeIgniter I will certainly try it and see

edit.. I have just re-read the form validation class information in the userguide and in there it mentions using the set_select function to quote the code example there they suggest this format
Code:
<select name="myselect">
<option value="one" &lt;?php echo set_select('myselect', 'one', TRUE); ?&gt; >One</option>
<option value="two" &lt;?php echo set_select('myselect', 'two'); ?&gt; >Two</option>
<option value="three" &lt;?php echo set_select('myselect', 'three'); ?&gt; >Three</option>
</select>
Now, theoretically I could add, echo set_select('myselect', one) etc to each array element in the generate list method in my model, but, of course I could be completely wrong about all this what do you think?
#4

[eluser]CroNiX[/eluser]
Lets see your view file...where you are generating your select element.
Are you using the form helper?
http://ellislab.com/codeigniter/user-gui...elper.html
Read about generating the select... form_dropdown();

Here a working example:
Controller:
Code:
&lt;?php
class Test extends Controller
{
    function Test()
    {
        parent::Controller();
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<p style="font-weight:bold; color:red">', '</p>');
    }

    function index()
    {
        $data = array();
        //create the form options, store in data variable to be sent to view
        $data['form_options'] = array(
            ''        => 'Select One',  //leaving the default key empty so we can use the "required" validation rule
            'one'    => 'First Choice',
            'two'    => 'Second Choice'
        );
        //define the validation rules
        $this->form_validation->set_rules('myselect', 'Select One', 'required');
        
        $status = 'Welcome, please fill out the form.';
        //if the form was submitted
        if($this->input->post('submit'))
        {
            //if validation failed
            if($this->form_validation->run() === FALSE)
            {
                $status = 'Please correct the form errors and try again.';
            }
            else
            {
                //validation passed
                $status = 'Your form has been submitted.  Thank you.';
            }
        }
        //update the status and store in the data variable
        $data['status'] = $status;
        //generate the view and pass the data
        $this->load->view('test_view', $data);
    }
}
View File:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
&lt;html &gt;
&lt;head&gt;
&lt;title&gt;Form Dropdown/Validation/Repopulation&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
<p>&lt;?php echo $status; ?&gt;</p>
&lt;?php echo form_open('/test'); ?&gt;
<p>
    &lt;?php echo form_label('Select One:&nbsp;', 'myselect'); ?&gt;
    &lt;?php echo form_dropdown('myselect', $form_options, set_value('myselect', ''), 'id="myselect"'); ?&gt;
</p>
&lt;?php echo form_error('myselect'); ?&gt;
<p>&lt;?php echo form_submit('submit', 'Submit Form'); ?&gt;</p>
&lt;?php echo form_close(); ?&gt;
&lt;/body&gt;
&lt;/html&gt;
#5

[eluser]edjon2000[/eluser]
Hi CroNiX, thanks for your reply and your examples,

I have been playing about with this all day and have a solution of sorts, here is the first part my current view file (I have a common header and footer, and yes I am using the form helper
Code:
&lt;?php if(!$_POST) $_POST = NULL; ?&gt;
<h1>&lt;?php echo $page_title; ?&gt;</h1>
<div id="featured-content-upper"></div>
<div id="featured-content-middle">
    <div id="vacancy-add" class="add-vac-form">
        &lt;?php echo form_open('add_vacancy'); ?&gt;
        &lt;?php echo form_fieldset('Client Information'); ?&gt;
        <div class="form-column-medium">
            <label for="client_name">Clients Name<span class="req">required</span></label>
            &lt;input type="text" name="client_name" id="client_name"
                         value="&lt;?php echo set_value('client_name'); ?&gt;"
                         title="Please enter clients name (required field)"
                         size="50" maxlength="50" /&gt;
            &lt;?php echo form_error('client_name'); ?&gt;

            <label for="client_address">Clients Address</label>
            &lt;textarea name="client_address" id="client_address"
                                title="Please enter clients address if applicable"
                                rows="7" cols="15"&gt;&lt;?php echo set_value('client_address'); ?&gt;&lt;/textarea&gt;
            &lt;?php echo form_error('client_address'); ?&gt;
        </div>
        <div class="form-column-medium">
            <label for="client_phone">Clients Phone Number</label>
            &lt;input type="text" name="client_phone" id="client_phone"
                         value="&lt;?php echo set_value('client_phone'); ?&gt;"
                         title="Please enter clients 'phone number if applicable"
                         size="50" maxlength="50" /&gt;
            &lt;?php echo form_error('client_phone'); ?&gt;

            <label for="client_email">Clients Email Address</label>
            &lt;input type="text" name="client_email" id="client_email"
                         value="&lt;?php echo set_value('client_email'); ?&gt;"
                         title="Please enter a valid email address if applicable"
                         size="50" maxlength="50" /&gt;
            &lt;?php echo form_error('client_email'); ?&gt;

            <label for="client_postcode">Clients Postcode</label>
            &lt;input type="text" name="client_postcode" id="client_postcode"
                         value="&lt;?php echo set_value('client_postcode'); ?&gt;"
                         title="Please enter clients postcode if applicable"
                         size="50" maxlength="50" /&gt;
            &lt;?php echo form_error('client_postcode'); ?&gt;
        </div>
        &lt;?php echo form_fieldset_close(); ?&gt;

        &lt;?php echo form_fieldset('Vacancy Information'); ?&gt;
        <div class="form-column-medium">
            <label for="vacancy">Vacancy Name<span class="req">required</span></label>

            &lt;?php    echo form_dropdown('vacancy',    $vac_name, set_value('vacancy', $_POST['vacancy']), 'id="vacancy"'); ?&gt;

            <label for="salary">Salary<span class="req">required</span></label>

            &lt;?php    echo form_dropdown('salary', $sal_name, set_value('salary', $_POST['salary']), 'id="salary"'); ?&gt;
        </div>
        <div class="form-column-medium">
            <label for="sector">Sector<span class="req">required</span></label>

            &lt;?php echo form_dropdown('sector', $sec_name, set_value('sector', $_POST['sector']), 'id="sector"'); ?&gt;

            <label for="loc">Location<span class="req">required</span></label>
            &lt;?php
            echo form_input('location', 'Type a location', 'id="loc"');
            ?&gt;
        </div>
        <br class="clear" />
        <div class="form-column-wide">
            <label for="description" class="desc">Description</label>
            &lt;textarea name="vacancy_desc" id="description"
                                title="Please enter vacancy description if applicable"
                                rows="10" cols="20" class="desc"&gt;
            &lt;?php echo set_value('vacancy_desc'); ?&gt;
            &lt;/textarea&gt;
            &lt;?php echo form_error('vacancy_desc'); ?&gt;
#6

[eluser]edjon2000[/eluser]
and here is the second part
Code:
<br class="clear" />
            <div class="button-array">
                <table>
                    <caption>Is Vacancy Active?<span class="req">required</span></caption>
                    &lt;?php
                    /** active vacancy radio group * */
                    $data = array();
                    $data = array(
                            'name' => 'vacancy_active',
                            'id' => 'vacancy_active_0',
                            'value' => 'Yes',
                            'checked' => TRUE,
                    );
                    ?&gt;<tr>
                        <td>&lt;?php echo form_label('Yes', 'vacancy_active_0'); ?&gt;</td>
                        <td>&lt;?php echo form_radio($data); ?&gt;</td>
                        &lt;?php
                        $data = array();
                        $data = array(
                                'name' => 'vacancy_active',
                                'id' => 'vacancy_active_1',
                                'value' => 'No',
                                'checked' => FALSE,
                        );
                        ?&gt;
                        <td>&lt;?php echo form_label('No', 'vacancy_active_1'); ?&gt;</td>
                        <td>&lt;?php echo form_radio($data); ?&gt;</td>
                        &lt;?php echo form_error('vacancy_active'); ?&gt;
                    </tr>
                </table>
                <table>
                    <caption>Featured Vacancy<span class="req">required</span></caption>
                    &lt;?php
                    /** featured vacancy radio group * */
                    $data = array();
                    $data = array(
                            'name' => 'vacancy_featured',
                            'id' => 'vacancy_featured_0',
                            'value' => 'Yes',
                            'checked' => FALSE,
                    );
                    ?&gt;
                    <tr>
                        <td>&lt;?php echo form_label('Yes', 'vacancy_featured_0'); ?&gt;</td>
                        <td>&lt;?php echo form_radio($data); ?&gt;</td>
                        &lt;?php
                        $data = array();
                        $data = array(
                                'name' => 'vacancy_featured',
                                'id' => 'vacancy_featured_1',
                                'value' => 'No',
                                'checked' => TRUE,
                        );
                        ?&gt;
                        <td>&lt;?php echo form_label('No', 'vacancy_featured_1'); ?&gt;</td>
                        <td>&lt;?php echo form_radio($data); ?&gt;</td>
                        &lt;?php echo form_error('vacancy_featured'); ?&gt;
                    </tr>
                </table>

                &lt;?php echo form_submit('submit', 'Check Entry'); ?&gt;
            </div>
        </div>

        &lt;input name="town_id" type="hidden" id="town_id" /&gt;
    &lt;input name="county_id" type="hidden" id="county_id" /&gt;
    &lt;input name="bs" type="hidden" id="bs" /&gt;

        &lt;?php echo form_fieldset_close(); ?&gt;

        &lt;?php echo form_close(); ?&gt;

    </div>

</div>
<div id="featured-content-lower"></div>

I had to split it over 2 posts

so far everything works correctly apart from the salary dropdown for some reason that defaults to the first entry every time.

I am thinking that I must be missing something somewhere.
#7

[eluser]edjon2000[/eluser]
I am generating my list elements from my model which I have modified a bit
Code:
function generate_vacancy_list() {
        /**
         * Generate return array for vacancy field dropdown options
         */
                $vacancy_keys = array();
                $vacancy_keys_arr = array();
                $vacancy_vals_arr = array();

        $vacancy_keys = $this->db->query('SELECT DISTINCT(vac_list_name) FROM vacancy_list ORDER BY vac_list_id');

        foreach ($vacancy_keys->result_array() as $vacancy_key) {
            $vacancy_keys_arr[] = $vacancy_key['vac_list_name'];
            $vacancy_vals_arr[] = $vacancy_key['vac_list_name'];
        }

        $query = array_combine($vacancy_keys_arr, $vacancy_vals_arr);

        return $query;
    }

    /**
     * The generate_sector_list method generates the data to populate
     * the sector dropdown menu for the vacancy search form
     *
     * Returned object (array of)
     * --------------------------
     * sec_list_name
     *
     * @return array
     */
    function generate_sector_list() {
        /**
         * Generate return array for sector field dropdown options
         */
                $sector_keys = array();
                $sector_keys_arr = array();
                $sector_vals_arr = array();

        $sector_keys = $this->db->query('SELECT DISTINCT(sec_list_name) FROM sector_list ORDER BY sec_list_id');

        foreach ($sector_keys->result_array() as $sector_key) {
            $sector_keys_arr[] = $sector_key['sec_list_name'];
            $sector_vals_arr[] = $sector_key['sec_list_name'];
        }

        $query = array_combine($sector_keys_arr, $sector_vals_arr);

        return $query;
    }

        function generate_salary_list() {
        /**
         * Generate return array for salary field dropdown options
         */
                $salary_keys = array();
                $salary_keys_arr = array();
                $salary_vals_arr = array();

        $salary_keys = $this->db->query('SELECT DISTINCT(sal_list_amount) FROM salary_list ORDER BY sal_list_id');

        foreach ($salary_keys->result_array() as $salary_key) {
            $salary_keys_arr[] = $salary_key['sal_list_amount'];
            $salary_vals_arr[] = $salary_key['sal_list_amount'];
        }

        $query = array_combine($salary_keys_arr, $salary_vals_arr);

        return $query;
    }

These are called from my controller at this point
Code:
function add_vacancy() {
        /** rules for form validation * */
        $this->form_validation->set_error_delimiters('<span class="flashError">', '</span>');

        $this->form_validation->set_rules('client_name', 'Clients Name', 'trim|required|min_length[3]|max_length[50]');
        $this->form_validation->set_rules('client_address', 'address', 'trim|max_length[1024]');
        $this->form_validation->set_rules('client_phone', 'phone number', 'trim|min_length[3]|max_length[50]');
        $this->form_validation->set_rules('client_email', 'email address', 'trim|min_length[3]|max_length[50]|valid_email');
        $this->form_validation->set_rules('client_postcode', 'postcode', 'trim|min_length[3]|max_length[10]');
        $this->form_validation->set_rules('vacancy_name', 'vacancy', 'trim');
        $this->form_validation->set_rules('vacancy_salary', 'salary', 'trim');
        $this->form_validation->set_rules('vacancy_sector', 'sector', 'trim');
        $this->form_validation->set_rules('vacancy_area', 'location', 'trim');
        $this->form_validation->set_rules('vacancy_desc', 'description', 'trim|max_length[5000]');
        $this->form_validation->set_rules('vacancy_active', 'please select an option', 'required');
        $this->form_validation->set_rules('vacancy_featured', 'please select an option', 'required');



        if ($this->form_validation->run() == FALSE)
        {
            /** rebuild add vacancy page view with errors if unsuccessful * */
            $data = array();
            $data['page_title'] = 'Add New Vacancy';
            $data['main_content_1'] = 'admin_views/admin_add_vac_view';

            $data['vac_name'] = $this->vacancy_model->generate_vacancy_list();
            $data['sec_name'] = $this->vacancy_model->generate_sector_list();
            $data['sal_name'] = $this->vacancy_model->generate_salary_list();

            $this->load->view('includes/template', $data);
            //echo "<h1>Here is the add new vacancy page</h1>";


        }
        else
        {
            //load the check vacancy page
            $this->load->view('admin_views/test');
        }
    }
#8

[eluser]CroNiX[/eluser]
Try changing
Code:
function generate_vacancy_list() {
        /**
         * Generate return array for vacancy field dropdown options
         */
                $vacancy_keys = array();
                $vacancy_keys_arr = array();
                $vacancy_vals_arr = array();

        $vacancy_keys = $this->db->query('SELECT DISTINCT(vac_list_name) FROM vacancy_list ORDER BY vac_list_id');

        foreach ($vacancy_keys->result_array() as $vacancy_key) {
            $vacancy_keys_arr[] = $vacancy_key['vac_list_name'];
            $vacancy_vals_arr[] = $vacancy_key['vac_list_name'];
        }

        $query = array_combine($vacancy_keys_arr, $vacancy_vals_arr);

        return $query;
    }
to something like
Code:
function generate_vacancy_list() {
  $vacancy_keys = $this->db->query('SELECT DISTINCT(vac_list_name), vac_list_id FROM vacancy_list ORDER BY vac_list_id')->result_array();  //you weren't getting the ID in your query, which is needed

  $data = array();
  foreach($vacancy_keys as $key)
  {
    //data passed to the form_dropdown must be an array in the form of array(option_key => option_value, option_key => option_value, ...)
    $data[$key['vac_list_id']] = $key['vac_list_name'];
  }
  return $data;
}
Please look closely at my working example. Compare everything I'm doing to the way you are for troubleshooting.
#9

[eluser]edjon2000[/eluser]
Hi CroNiX,

Thanks for that, I will check it out after I have had a bit of sleep and post back (it's like 03:45 here in the UK)
#10

[eluser]edjon2000[/eluser]
Ok I have gone through the code example you posted (nice piece of coding btw) and yes it works great, however, for the purposes of this project I need the dropdown/select list to have identical option values and option labels for the subsequent search, I created separate tables for the dropdown listings to avoid duplicates appearing in the dropdown menus, the actual search is against a separate table which contains all of the information per vacancy some of which is only for the site admin to access but the rest is for the site user to access, I know that, ideally, everything should be in separate tables with a load of id's in the master table but I had to work with what I had been given and I am also wanting to get this site live as soon as possible it's already taken longer than it should due to a complete rewrite/redesign from scratch, the first incarnation of the project was written in a traditional non-mvc way with a completely different design where form validation was done using the spry framework which of course ended up creating huge web pages with lots of duplicate code and it would have become a nightmare to update, my ultimate aim is to have each web page load after caching in 1 second or less.

I would like my returned array to be more like
Code:
......

    [client_email] => [email protected]
    [client_postcode] => aa1 1aa
--&gt; [vacancy] => Divisional Manager <--
    [salary] => £32 - 40k
    [sector] => Finance / Banking
......
Rather than
Code:
......
    [client_email] => [email protected]
    [client_postcode] => hj67yh
--&gt; [vacancy] => 13 <--
    [salary] => £20 - 25k
    [sector] => Hospitality
......

if there is any more information you need I will post it




Theme © iAndrew 2016 - Forum software by © MyBB