Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: using post when mutliple form fields share same name & id

That title probably doesn't mean much but what I have is a form that is generated dynamically. I hooks into a table of products, pulls out there name. I then create a form that displays the product with a checkbox and textbox next to it.

<form id="twitter-feed" name="twitter-feed" action="<?php echo $this->getUrl('tweet/') ?>index/tweet" method="post">
<table><tr>
<?php

$model = Mage::getModel("optimise_twitterfeed/twitterfeed");

$products = $model->getProducts();

foreach ($products as $product){
    echo '<tr>';
        echo '<td>';
            echo '<label for="'. $product .'">' . $product . '</label>';
            echo '<br /><input type="text" class="hashtag" name="tags" id="tags" value="#enter, #product, #hastag"';
        echo '</td>';
        echo '<td><input type="checkbox" name="chk" id="'. $product .'"></td>';
   echo '</tr>';
}
?>

<tr><td colspan="2"><input type="submit" name="submit" value="tweet"></td></tr>
</table>
</form>

As you can see there are checkboxes and textfields for each record. When I examine the $_POST data from the form it only retains fields for the last record.

Is there a way to pass all this data back to the action?

Cheers,

Jonesy

like image 246
iamjonesy Avatar asked Nov 29 '22 11:11

iamjonesy


2 Answers

Use name="chk[]", then PHP will create an array for you.

like image 80
ThiefMaster Avatar answered Dec 01 '22 00:12

ThiefMaster


Change your name arrtibutes to have an opening and closing square brace like this:

name="tags"
name="chk"

to

name="tags[]"
name="chk[]"

This will turn an array like:

$_POST['tags'][0] = VALUE
$_POST['tags'][1] = VALUE

$_POST['chk'][0] = VALUE
$_POST['chk'][1] = VALUE
like image 29
a1phanumeric Avatar answered Nov 30 '22 23:11

a1phanumeric