laravel 4 - Input old for arrayed checkbox - php

I have a loop of checkboxes with multiple attributes. One content may have many attributes, so user can check more than one attribute.
If some validation errors occurs in this form I need to pre-fetch already checked attribute.
#foreach($attributes as $entry)
<div class="check-line">
<input type="checkbox" id="cat4" class='icheck-me'
name="attribute[<?php echo $entry->id; ?>]"
data-skin="square"
data-color="blue"
value="{{$entry->id}}"
<?php
if(Input::old('attribute['.$entry->id.']')== $entry->id) {
echo 'checked="checked"';
}
?>
/>
<label class='inline' for="cat4">
<strong>{{$entry->name}}</strong>
</label>
</div>
#endforeach
I tried above but no luck.. any ideas?

From Laravel docs on Requests:
"When working on forms with "array" inputs, you may use dot notation to access the arrays:"
$input = Input::get('products.0.name');
So you should be able to do this fpr Input::old() as well:
<?php
if(Input::old('attribute.' . $ii) == $entry->id) {
echo 'checked="checked"';
}
?>

A slightly more catch-all answer to this would be to do an array search rather than just checking the current index. As such, I see the code looking like this:
#foreach($attributes as $entry)
<div class="check-line">
<input type="checkbox" id="cat4_{{{ $entry->id }}}" class="icheck-me"
name="attribute[]"
data-skin="square"
data-color="blue"
value="{{{ $entry->id }}}"
#if (in_array($entry->id, Input::old('attribute')))
checked
#endif
/>
<label class="inline" for="cat4_{{{ $entry->id }}}">
<strong>{{{ $entry->name }}}</strong>
</label>
</div>
#endforeach
So first off I've made the code more Blade-compliant:
Any echos are now {{{ and }}} rather than the previous mix of <?php echo ___; ?> and {{/}} (I went for {{{ rather than {{ as it's not HTML being echoed and it's better to be safer)
The <?php if () { is now a Blade #if ()
The name attribute is now just a standard array (doesn't include indices, as it doesn't need to), however the id attribute previously gave all checkboxes the same ID. While browsers will let you do this, it's technically illegal HTML, so I've appended the entry ID to each checkbox.
Finally, the if condition no longer checks that the value of the input with the current index matches the current entry's ID, but instead searches to see if the current entry's ID is anywhere in the returned array. This protects against the possibility of your entries being returned in a different order to the previous time they were on the page.
We now don't have a reliance on the $ii variable, so it can be removed too.
Caveats:
In doing this I've made the code a little nicer, but the code is no longer identical. Without knowing exactly why you use the $ii variable in order to provide keys to your attribute array I can't say that using my code will work correctly. However, assuming it was just there to help with this old input thing, then it's fine.
Also, my change of {{ to {{{ may have consequence I don't know about. I'd have thought for the $entry->id stuff it'd be fine, but maybe $entry->name in the <label> need to be unescaped HTML for a reason. Feel free to change this back.

Related

Foreach with 2D (Multi-Dimensional) input names, how to grab the data & update database?

I have looked everywhere so I apologize if there's an answer to this already, I couldn't find it after hours of searching. Maybe it's not a good way to do it either...
I have a form that has "picks" of a litter, so 1st pick, 2nd pick, 3rd pick, etc. These picks also have genders (Female, Male)
I use a foreach query to grab the available pick spots. If someone isn't assigned to that pick spot, then the input field is enabled for manual typing
Within that foreach query, I need to somehow submit what pick it is and what gender, as well as the typed value, so I can find the pick and store it to the database... The other problem is, it's dynamic where someone may type in 3 input fields, or other times just 1 input field. Basically it'll show 3 input fields and the user can choose to use all 3 or just 1...
No matter what I've tried, it doesn't work. I don't even have my examples because I've tried everything I could find and had to scrap it all
The input, this is for males only but females are the same:
<?php
foreach ($malespickedquery as $pick){
$picktaken=$pick['user_id'];
$pickcustom=$pick['custom_name'];
$pickposition=$pick['pick_id'];
$suffix=ordinal($pickposition);
?>
<div class="form-row pb-3">
<div class="col-12">
<label class="control-label"><?php echo $pickposition.$suffix." Pick "; ?>Male:</label>
<?php if($pickcustom==true){ ?>
<input type="text" name="" class="form-control" value="<?php echo $pickcustom; ?>" />
<?php }elseif($picktaken!="0"){ ?>
<input type="text" name="" class="form-control" value="<?php echo $pick['public_name']; ?>" disabled />
<?php }else{ ?>
<input type="text" name="malepicks[<?php echo $pickposition; ?>][male][]" class="form-control" value="" />
<?php } ?>
</div>
</div>
<?php } ?>
I've tried foreach within foreach, but can never get all information. Most things just return the last input field as well... So if 3 of them are generated, the last input field would come through but not the others. I also did something with foreach where it returned ALL of the fields, even blank ones, which just got confusing and still didn't work right
Thank you in advance!

Sending checked checkbox values

I'm doing a filter-by specifications on an app, and was wondering how can I implement without reloading the whole page (which I'm trying to convert to AJAX rather than PHP/Laravel alone). However my filters are based off on foreach loops
#foreach($cores as $core)
<li style="list-style: none;">
<input type="checkbox" name="core[]" id="cores" class="form-check-control" value="{{ $core->value }}"> {{ $core->value }}
</li>
#endforeach
Am trying $('#cores').val() but it is not working. I'm thinking of call it by class name then looping it to check if it is checked but it may affect performance.
The for loop is creating multiple elements with the same id, so accessing it this way won't work. Remove the id element from the checkbox, and refer to this answer for getting the value of the checked boxes in JS
try to do it this way and u can take the values
#foreach($cores as $core)
<li style="list-style: none;">
<input type="checkbox" name="core[{{ $core->value }} || paste something unique for the checkbox]" id="cores" class="form-check-control" value="1"> {{ $core->value }}
</li>
#endforeach
after that u can foreach $core and take only values that are seted and filter by them

PHP send array to another PHP file

This may be a stupid question but I'm lost here. I need to send array with some data in it to another PHP file using POST variable. This is my form:
<form action="test.php" method="post">
<label name="html[]" hidden><?php echo $array; ?></label>
<input type="submit" value="submit">
</form>
And this is test.php
<?php
$html = $_POST['html'];
for($i = 1; $i<=9; $i++){
echo $html[$i];
}
?>
So this is what I tried, but it's not displaying anything. please help
You need to create a number of input elements with the same name, each of which will have one array item as its value:
<?php foreach ($array as $item) : ?>
<input type="hidden" name="html[]" value="<?= htmlspecialchars($item); ?>" />
<?php endforeach; ?>
Important points to keep in mind:
$item must always be a scalar value (string, integer, etc). You cannot pass in arrays piecemeal with this technique.
Never forget that since you are injecting variables into HTML output you must escape and/or sanitize them properly. In this case this is done with htmlspecialchars, which must know about your output encoding to work correctly in general (look up its third parameter).
There is also an alternative approach that can be used to pass arrays piecemeal through serialization:
<input type="hidden" name="html"
value="<?= htmlspecialchars(serialize($array)); ?>" />
And you would then unserialize it on the receiving end:
$html = unserialize($_POST['html']);
I 'm mostly including this option for completeness, as in practice session variables are a much better way of passing complex state between requests.
Is it necessary to put the data of the array in a hidden field? You can store the array in $_SESSION and access it. Btw, I think you have a problem, labels can be submitted, in that case you must put the data into an input field with type="hidden".

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.

Deleting a database record using $_POST with Codeigniter

I've been doing it all wrong, I used to take the value from the URI segment and didn't realize it wasn't the ideal way. So I changed my approach and now have everything via a $_POST. I'm not sure if I'm doing this correctly, could someone shed some light? My view contains tabular data listing items pulled from the DB. Each item has two links, "View" and "Delete." The code seems to work but was wondering if it could be coded better. I forgot that the form name wasn't unique, so when I went to go delete a record, it would always delete the newest record (the last hidden field was set).
myview.php (snippet)
<?php foreach($records as $record): ?>
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
View Delete
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
</form>
<?php endforeach ?>
Viewing/Deleting via uri id is perfectly fine, I wouldn't venture to say that using $_POST is wrong, but creating a new unique form for every delete element is terribly messy, and weighed against what you are gaining (no exposed id i guess?), I believe it is more 'correct' to use the uri for delete functions.
If you only want certain people to be able to delete certain records, handle that programmatically in the delete function itself, don't depend on the fact that the request is only sent via $_POST. This is not dependable, anyone can generate a post request.
For anyone who comes across this later, here's how I solved my issue.
In my controller I have a method called delete that checks to see if the form field was submitted via a $_POST. If there's no variable, redirect them somewhere with an error message. If the field was passed, then go through the normal checks to make sure the record can be deleted.
if(!isset($_POST['item_id']))
{
$this->session->set_flashdata('message', 'item cannot be removed!');
redirect("/item");
}
if($this->input->post('item_id')) {
... code ....
... code ....
}
Your syntax error is with this line:
<?php foreach($records as $record): ?>
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
View <a href="#" onclick="document.myform<?php echo
$location->id;?>.submit();">Delete</a>
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
</form>
<?php endforeach ?>
You can not do looping for a form. Instead, use the following code:
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
<?php foreach($records as $record): ?>
a href="/location/view/<?php echo $location->id;?>">View</a> Delete
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
<?php endforeach ?>
</form>

Categories