kohana parse $_POST data
i have a kohana application, and i have a form with several checkboxes, and the user is supposed to check his preferences there in the form. so i have a relation 1:n between the user table and the preferences table. my problem is that i want to save those preferences, selected in the form, and i don;t know how.
i have the form:
<form id="address" method="POST" action="<?= Route::url('Save user preferences' , array('user_id' => $user));?>">
<? foreach ($prefered_products as $pp): ?>
<input type="checkbox" name="user_preferences_preference[]" value="<?= $pp ?>" /><?= $pp->product; ?><br />
<? endforeach; ?>
<button type="submit">Salveaza preferintele tale</button>
</form>
and i save the data:
foreach ($_POST['user_preferences_preference'] as $up) {
$user_preferences->prefered = $up;
$user_preferences->user = $this->user;
$user_preferences->save();
}
$this->view->message = __('Thank you for your feedback!');
but seems like the way i parse the preferences is not correct, i am getting: ErrorException [ Warning ]: Invalid argument supplied for foreach()
any 开发者_开发问答idea about how am i supposed to get the multiple $_post preferences? thank you!
I have a slightly different way of doing this.
When I create a checkbox I also create an identical hidden field set to zero
<input type="hidden" name="my_check" value="0" />
<input type="checkbox" name="my_check" value="$value" />
The checkbox, if ticked, will override the hidden value. This way when you send the form you end up with $_POST['checkbox]=1 or 0, but it always exists in the $_POST.
The nice thing about this method is you can extend the Form::checkbox helper so that it's always present and you don't have to worry about it for every form / controller.
p.s. in you above example you would probably want to do it like this:
<input type="hidden" name="user_preferences_preference[$pp->id]" value="0" />
<input type="checkbox" name="user_preferences_preference[$pp->id]" value="<?= $pp ?>" />
<?= $pp->product; ?><br />
Or use a $key value instead of $pp->id.
The problem is that a checkbox will only post data when set. You should reverse check the values. Ie;
- Fetch all preference (id's) from the database
- Check if a value is found in the $_POST var
- If not, update to false (or 0 or whatever) in db, if set, read out the value.
精彩评论