Search code examples
codeigniterphpcodeigniter-form-helper

get form values other than by name in codeigniter


hi i am using codeigniter . i have a form , there i add hidden fields dynamically . so every hidden field is <input type='hidden' name='hidden' value="+$(this).attr('title')+"> so the name is equal .

the problem is when i submit the form and try to get my hiden field values i can only get one hidden field value , because the names are same

i print my form values

print_r($this->input->post());

i have 2 hidden fields but i get only one

Array
(
    [hidden] => march
    [textbox] => march
    [mysubmit] => Submit
)

i can change the name dynamically of hidden field when creating , but then i don't know exactly the name of my hidden field ,

how can i get hidden field values with same name ?? is there any way to get form values other than by name ?? i tried and can not find an answer , please help .............


Solution

  • You'll need to use brackets in your name attributes:

    <input type='hidden' name='hidden[]'>
    <!--                            ^^^^                                   -->
    

    This will allow PHP to accept multiple inputs with the same name as an array of values, so in this case, $_POST['hidden'] will return an array of strings.

    By default they are indexed starting at 0, so $_POST['hidden'][0] will get you the first one, $_POST['hidden'][1] will get you the second, etc., however - you can explicitly index them if it's easier for you, either with numbers or strings.

    <input type='hidden' name='hidden[first]'>
    <input type='hidden' name='hidden[second]'>
    

    Or:

    <input type='hidden' name='hidden[0]'>
    <input type='hidden' name='hidden[1]'>
    

    You can nest these as deep as you want like hidden[first][1][], and they will be treated similarly to a PHP array when you get the $_POST values, but you need the brackets in the HTML.

    Without brackets, only the last field's value will be available in the $_POST array. This is a PHP feature, Codeigniter can't do anything about it.