Welcome Guest, Not a member yet? Register   Sign In
Array Form Validation
#1

[eluser]wdcmatt[/eluser]
I was looking for a way to validate an array of data that was coming in as a form. And I found it sparsely documented on the user guide, So I post my findings here hoping it will help someone trying to do what I was.


I was building a menu form that had the following fields, menu_id, menu_order, menu_entry. I wanted to create a form containing 2 text fields per row (order and entry) to be edited by a user, and this list was to grow dynamically as they added menu items.... I found this difficult, so I wanted to tinker with using arrays so that my form element names where an array of the data I was looking for. This ties into a sql db with 1 table with 3 fields (menu_order, menu_id, menu_name).

So the form looks something like this:

Code:
echo form_open('menu/list');
foreach( $entry_from_db->result() as $entry)
{
    $id = $entry->menu_id;
    $data = array(
        'name'        => "menu_order[$id]",
        'id'          => "menu_order[$id]",
        'value'       => $entry->menu_order,
        'size'        => '50',
     );
                
    $data1 = array(
        'name'        => "menu_name[$id]",
        'id'          => "menu_name[$id]",
        'value'       => $entry->menu_name,
        'size'        => '50',
    );
    $output .= form_input($data). form_input($data1). "<br />";
}
form_submit('submit', 'Edit Menu');

Then to validate all of the entries, I did this:

Code:
function list()
{
    // I can do this becuase menu_name and menu_order must have the same key....
    // not sure if the $_POST is the right thing to call here ... but works
   foreach($_POST['menu_order'] as $key => $value)
   {
       $rules[] = array('field' => "menu_order[$key]", 'label' => "Menu Order $key", 'rules' => 'trim|required|integer');
       $rules[] = array('field' => "menu_name[$key]", 'label' => "Menu Name $key", 'rules' => 'trim|required|max_length[50]');
    }
    
    $this->form_validation->set_rules($rules);
        
    // validate the data
    if (($this->form_validation->run() !== FALSE))
    {
        echo 'true;';
    }
    else
    {
        echo 'false';
        echo validation_errors();
    }
}

This will validate EVERY entry on the page reguardless of the quantity. Of course in a live script you would need to have a callback function that tests for unique entries, and validates the ID's, but this should be enough to get someone rolling the the right direction on arrays in form processing.

I guess my point is you can specify array keys in the form validation process, their by making it much more handy to process an unknown number of entries that all have to have the same type of validation. I didn't know this, and it wasn't very clear in the user guide.

Hope this helps someone.




Theme © iAndrew 2016 - Forum software by © MyBB