How can I add objects that I have already returned from my database to an array on form submit? I am retrieving all of my players from my database like so,
$players = Player::all();
and outputting them like this:
<form>
@foreach($players as $player)
<ul>
<li>
<input type="checkbox" name="{{ $player->id }}">
{{ $player->fn }} {{ $player->ln }}
</li>
</ul>
@endforeach
<input type="submit" value="Submit">
</form>
This is what I consider my "player pool", where all players are loaded and available to be "checked" in. I am simply trying to have two sections on this page, one that has the player pool, and one that shows the selected players from the players pool. When a player is checked in they are added to the "players in game" section below the "player pool", and will be part of a new form that can again be submitted, but to the database instead of the same just to the page. How would I achieve this with JSON and PHP?
To be honest, I'm not sure how you want to use JSON for this, but you probably want to use the player ID as the value for the checkbox rather than the name.
<input type="checkbox" name="player_ids[]" value="{{ $player->id }}">
Then you will have an array of player IDs in $_GET['player_ids'] (or $_POST['player_ids'] if this ends up being a POST form.)
You will want to give you form a class so you can begin building a jQuery function to select the players as a checkboxes within the form become checked.
Say,
<form class="player_form">
</form>
With the form structure you propose in your question, the firstname and lastname (I am assuming) are just echoes next to the box. If you are wanting submit these in a later form you will need to have these as input fields, like your checkbox:
<input type="text" name="player_name" value="{{$player=>fname}}" />
I think you want to move all of the information within a li element if the checkbox within that li is checked. To do this, you can add a listener to the checbox using change. You can also use click but this won't listen on the event where the box is checked by keyboard!
$(document).ready(function(){
$(".player_form :checkbox").change( function() {
var player = $(this).closest("li");
//Now add this point into your new form
$(".my_submit_form").append(player);
)}
});
The closest function will traverse up the dom and find the closest li element and then append this data to your new form.
I would suggest you reconsider your form naming convention. As you have it you will be submitting a unique name with every checkbox, I don't think this is what you mean to say.
<li>
<input type="checkbox" name="player_id[]" value="{{$player->id}}" />
<input type="text" name="player_fname[]" value="{{$player=>fname}}" />
<input type="text" name="player_lname[]" value="{{$player=lname}}" />
</li>
Would be something like what you want, for form handling. Don't forget the names must be submitted as an array (i.e player_id[]) because you will be submitting multiple players within a form!